/**
* 文件下载
*
* @param id
* @return
*/
@GetMapping("/downloadFile")
@ApiOperation(value = "文件下载")
public void downloadFile(HttpServletRequest request,HttpServletResponse response,@RequestParam("userId")String userId,@RequestParam("fileId")String fileId) {
byte[] buffer = new byte[1024];
try {
FileBean bean = fileStoreService.getFileInfo(userId,fileId);
String filePath = bean.getFilePath();
File file = new File(filePath);
if(file.exists()) {
InputStream in = new FileInputStream(file);
setHeader(request,response,bean.getName());
OutputStream outputStream = response.getOutputStream();
while(in.read(buffer,0,1024) != -1){
outputStream.write(buffer, 0, buffer.length);
}
}
fileStoreService.updateUserFile(userId,fileId,"download");
} catch (Exception e) {
log.error(e.getMessage());
}
}
private boolean setHeader(HttpServletRequest request, HttpServletResponse response, String fileName) {
try {
response.setContentType("application/octet-stream");
response.setHeader("content-type", "application/octet-stream");
String browser = request.getHeader("User-Agent");
if (-1 < browser.indexOf("MSIE 6.0") || -1 < browser.indexOf("MSIE 7.0")) {
// IE6, IE7 浏览器
response.addHeader("content-disposition", "attachment;filename="
+ new String(fileName.getBytes(), "ISO8859-1"));
} else if (-1 < browser.indexOf("MSIE 8.0")) {
// IE8
response.addHeader("content-disposition", "attachment;filename="
+ URLEncoder.encode(fileName, "UTF-8"));
} else if (-1 < browser.indexOf("MSIE 9.0")) {
// IE9
response.addHeader("content-disposition", "attachment;filename="
+ URLEncoder.encode(fileName, "UTF-8"));
} else if (-1 < browser.indexOf("Chrome")) {
// 谷歌
response.addHeader("content-disposition",
"attachment;filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8"));
} else if (-1 < browser.indexOf("Safari")) {
// 苹果
response.addHeader("content-disposition", "attachment;filename="
+ new String(fileName.getBytes(), "ISO8859-1"));
} else {
// 火狐或者其他的浏览器
response.addHeader("content-disposition",
"attachment;filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8"));
}
return true;
} catch (Exception e) {
log.error(e.getMessage());
return false;
}
}