1.代码实现
springboot自己集成了MultipartFile,可以在配置文件中设置上传文件大小的限制
@RestController
@RequestMapping("/file")
public class FileController {
@Value("${upload.path}")
public String uploadPath;
@PostMapping("/upload")
public boolean upload(MultipartFile file, String fileName){
if(file==null) return false;
if(fileName==null) fileName = file.getOriginalFilename();
try {
file.transferTo(new File(uploadPath+fileName));
} catch (IOException e) {
e.printStackTrace();
} finally{
return true;
}
}
@GetMapping("/download")
public void download(String path, HttpServletResponse response) throws Exception {
String fileName = null;
FileInputStream fis = null;
File file = new File(uploadPath+path);
if(path.contains("/"))fileName = path.substring(path.lastIndexOf("/"),path.length());
else fileName = path;//如果文件在根路径
if(!file.exists()) {errorPath("系统找不到指定的路径",response);return;}
if(file.isDirectory()) {errorPath("文件夹不可下载",response);return;}
//附件形式下载
response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8"));
response.setContentType("form/data;charset=utf-8");
FileCopyUtils.copy(fis,response.getOutputStream());
}
public void errorPath(String message,HttpServletResponse response) throws IOException {
response.setContentType("text/plain;charset=utf-8");
response.getWriter().write(message);
}
}
配置文件
server.servlet.context-path=/webfile
server.port=8888
upload.path=D:/
2.测试
1)文件上传采用postman测试
2)文件的下载可以直接在浏览器测试接口