1、加入依赖
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
2、编辑文件上传
@RequestMapping("/upload")
public String upload(MultipartFile file,HttpServletRequest request){
//获取文件名字
String filename = file.getOriginalFilename();
//定制唯一id
String uuId = UUID.randomUUID().toString();
//获取文件后缀
String[] strArray = fileName.split("\\.");
String suffix = strArray[strArray.length -1];
//设置唯一名字
String uniqueFeileName = uuid + "." + suffix;
//获得upload_file的磁盘路径
String realPath = request.getServletContext().getRealPath("/upload_file");
//创建文件
File folder = new File(realPath);
if (!folder.exists()) {
folder.mkdirs();
}
//上传文件
try {
file.transferTo(new File(folder, newName));
} catch (IOException e) {
e.printStackTrace();
}
//设置静态资源
String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/" + realPath +"/" + uniqueFeileName;
return url;
}
3、文件下载
/**
* 下载文件
* @param response
* @param id
* @throws IOException
*/
@GetMapping(value = "/download")
public void down(HttpServletResponse response, ,HttpServletRequest request,String fileName) throws IOException {
//获得要下载文件的绝对路径
String path = request.getServletContext().getRealPath("/upload_file")
//文件的完整路径
String real_path = path+"\\"+fileName;
response.setContentType("application/pdf");//文件
//设置响应头 告知浏览器,要以附件的形式保存内容 filename=浏览器显示的下载文件名
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(Files.readAllBytes(Paths.get(real_path)));
outputStream.flush();
outputStream.close();
}