接上篇文章,这里贴上如何将指定路径的文件通过response将文件保存至本地,供大家参考。
@RequestMapping("/download")
public String download(HttpServletResponse response, @RequestBody AttachFileVo attachFileVo) {
String fileUrl = attachFileVo.getUrl();
ServletOutputStream outputStream = null;
try {
File file = new File(fileUrl);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
fileInputStream.read(bytes);
fileInputStream.close();
response.setCharacterEncoding("utf-8");
String filename = attachFileVo.getName();
filename = (filename == null || filename == "") ?
fileUrl.substring(fileUrl.lastIndexOf("/") + 1) : filename;
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
response.setHeader("Content-Type", "application/octet-stream");
response.setHeader("Content-Length", "" + bytes.length);
outputStream = response.getOutputStream();
outputStream.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}