SpringBoot之文件上传与下载
前言
利用springboot2,我们可以很方便的弄上传和下载,今天刚刚好有个功能模块用到,所以share一下这个功能。
Controller控制器
控制器方面,只需要一个封装返回类(例如我用的ApiReturnUtil.success()/Reselt.ok()等,自行封装即可)、配置类(配置一下上传的路径以及映射出去的文件路径)、控制器主类(包含上传和下载的方法)即可。
@RestController
@RequestMapping("/image")
/**
* 文件上传控制器
* @author zhengkai.blog.****.net
**/
public class ImageController {
@Autowired
private MyProps myProps;
@PostMapping("save")
public ApiReturnObject save(@RequestParam("file") MultipartFile file,@RequestParam String checkNum,@RequestParam String facilityTypeNum) {
String fileName ="";
if(!file.isEmpty()){
if(!file.getOriginalFilename().contains(".")){
return ApiReturnUtil.error("上传失败:文件没有后缀名");
}
//文件名=设备类型-时间戳.后缀
fileName = facilityTypeNum.toUpperCase()+"-"+System.currentTimeMillis()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
String saveFileName = myProps.imagePath +checkNum+File.separator+fileName;
System.out.println(saveFileName);
File dest = new File(saveFileName);
if(!dest.getParentFile().exists()){
//判断文件父目录是否存在
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
//保存文件
} catch (Exception e) {
e.printStackTrace();
return ApiReturnUtil.error("上传失败:"+e.getMessage());
}
}else {
return ApiReturnUtil.error("上传失败:文件不存在");
}
Map<String,Object> returnMap=new HashMap<>(4);
//返回的时候把各种属性都返回即可
returnMap.put("imageUrl",myProps.getImageUrl()+checkNum+"/"+fileName);
returnMap.put("fileName","/"+checkNum+"/"+fileName);
returnMap.put("checkNum",checkNum);
returnMap.put("facilityTypeNum",facilityTypeNum);
return ApiReturnUtil.success(returnMap);
}
@RequestMapping("/download")
public Object download(HttpServletResponse response,@RequestParam String fileName) {
File file = new File( myProps.imagePath+fileName);
if (file.exists()) {
response.setContentType("application/force-download");
// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream outputStream = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
outputStream.write(buffer, 0, i);
i = bis.read(buffer);
}
return "下载成功";
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return ApiReturnUtil.error("文件不存在");
}
}
MyProps路径配置
imageUrl是上传后前缀补全路径,例如imageUrl=http://127.0.0.1:9999/
你上传了个a.jpg
在aaa
目录下,那么就是imageUrl/aaa/a.jpg
@Component
@ConfigurationProperties(prefix="system") //接收application.yml中的myProps下面的属性
@Data
public class MyProps {
public String imageUrl;
public String imagePath;
}
application.yml配置
- imagePath是本地存储主目录,linux的话是
/xxx/xxx
- imageUrl是项目的路径或者其他待映射路径
system:
imageUrl: http://127.0.0.1:9999/
imagePath: d:\\upload\\
HTML DEMO
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Blog.Csdn.Net/MoshowGame</title>
<meta charset="utf-8">
</head>
<body>
<form id="formData" enctype="multipart/form-data" method="post" action="http://localhost:8085/managesys/image/save">
<input name="checkNum" id="checkNum" value="21418419" /><br/>
<input name="facilityTypeNum" id="facilityTypeNum" value="Body001" /><br/>
<input type="file" name="file" id="file" value="" /><br/>
<a class="weui-btn-area">
<input class="weui-btn weui-btn_primary" type="submit" value="UPLOAD"/>
</a>
</form>
<form id="downData" method="post" action="http://localhost:8085/managesys/image/download">
<a class="weui-btn-area" onclick="download()">
<input name="fileName" id="fileName" value="\21418419\BODY001-1553004391258.doc" /><br/>
<input class="weui-btn weui-btn_primary" type="submit" value="DOWNLOAD"/>
</a>
</form>
</body>