文件上传下载功能一般会放在文件服务器中,前台直接拿到地址,直接请求地址,读取地址的相关信息,如果能解析该地址所对应的文件内容,就直接打开文件,展示内容。如果不能解析就下载文件。
但是有时我们也会将文件放在服务器上,以便及时下载,上传文件。
具体实现如下:
1.将工程部署到tomcat服务器上
2.在Java类中获取路径:
String basePath=this.getClass().getClassLoader().getResource("/").getPath();
int index=basePath.substring("WEB-INF");
String fileUrl=basePath.index(0,index)+"images/merShowImg/"+fileName+".jpeg";
使用文件输出流写文件到对应的位置上
FileOutputStream fos=new FileOutputStream(new File(fileUrl));
将前台图片用base64进行解码
byte[] outputBytes=new Base64().decode(photoImage);
fos.write(outputBytes);
fileUrl="../images/merShowImg/"+fileName+".jpeg";
--将该路径存储到数据库里面
cd.setFilePath(fileUrl);
将fileUrl发给前台即可。
注意:文件的后缀名一定带上,不然报错。