环境
代码部分
@Autowired
FileDownloadService downloadService;
/**
* 下载文件
* @param fileKey
* @param processId
* @param request
* @param response
* @return
*/
// @RequiresAuthentication
@RequestMapping("/download")
public String downloadFile(@RequestParam("fileKey") String fileKey, @RequestParam("processId") String processId, HttpServletRequest request, HttpServletResponse response){
return downloadService.downLoadFile(fileKey,processId,request,response);
}
/**
* 下载文件
*
* @return
*/
@Override
public String downLoadFile(String fileKey, String processId,
HttpServletRequest request,
HttpServletResponse response) {
RocFileSubmit fileSubmit = fileSubmitMapper.selectByFileKeyAndProcessId(fileKey, processId);
if (fileSubmit == null) {
//报异常
return null;
}
//文件路径
String fileUrl = fileSubmit.getUrl();
String fileName = fileSubmit.getName();
logger.info("【下载文件-文件名称】:"+fileName);
return down(fileUrl, fileName, request, response);
}
public String down(String fileUrl, String fileName, HttpServletRequest request, HttpServletResponse response) {
File file = new File(fileUrl);
if (file.exists()) {
//解决中文文件名乱码问题
String userAgent = request.getHeader("User-Agent");
// 针对IE或者以IE为内核的浏览器:
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
try {
fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// 非IE浏览器的处理:
try {
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
response.setContentType("multipart/form-data");
response.setCharacterEncoding("UTF-8");
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
// System.out.println("success");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return null;
}