紧连着上一条“上传文件”的文章
1、controller层
@RequestMapping(value="/downloadFile")
@ResponseBody
public Object downloadFile(@RequestParam(value="docId",required = false)String docId){
String filePath = "";
//普通类型文档下载
DocManager docManager = docManagerService.findDocById(docId);
if (docManager == null) {
return MarkUtil.markRetunMsg(false, "未找到文件!");
}
filePath = docManager.getDocPath() + docManager.getFileName();
File file = new File(filePath);
//下载文件到浏览器
try {
FileSystemResource fileSource = new FileSystemResource(file );
return FileUtil.downloadFile(fileSource.getInputStream(),fileSource.getFilename().substring(0,fileSource.getFilename().length()-6)); //保存到数据库的是带随机数的文件名fileName字段,因为将此文件名后面的六位随机数去掉
} catch (IOException e) {
return MarkUtil.markRetunMsg(false,e.getMessage());
}
}
FileUtil类中的downloadFile方法
/**
* 下载文件到默认浏览器
* @param in
* @param fileName
* @return
*/
public static ResponseEntity<InputStreamResource> downloadFile(InputStream in,String fileName) {
try {
byte[] testBytes = new byte[in.available()];
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", MarkUtil.convertFileName(fileName)));
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity
.ok()
.headers(headers)
.contentLength(testBytes.length)
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(in));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
MarkUtil类中的convertFileName方法如下:
/**
* chinese code convert
* @param fileName
* @return
*/
public static String convertFileName(String fileName) {
if(isContainChinese(fileName)) {
try {
fileName = URLEncoder.encode(fileName, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return fileName;
}