实现文件返回的Controller
第一种方法:
@RequestMapping(value = "/download", method = GET)
public ResponseEntity<byte[]> download(@RequestParam(Constant.PARAM_NAME_FILEPATH) String filePath,
HttpServletResponse response) throws Exception {
File file = fileSupport.getFile(filePath);
if (file == null) {
throw new FileNotFoundException(filePath + "不存在");
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", file.getName());
byte[] data = FileUtils.readFileToByteArray(file);
return new ResponseEntity<byte[]>(data, headers, HttpStatus.OK);
}
第二种方法:
@RequestMapping(value = "/download", method = GET)
public void download(@RequestParam(Constant.PARAM_NAME_FILEPATH) String filePath,
HttpServletResponse response) throws Exception {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
File file = fileSupport.getFile(filePath);
if (file == null) {
throw new FileNotFoundException(filePath + "不存在");
}
try {
long fileLength = file.length();
response.setContentType("text/plain;");
response.setHeader("Content-disposition", "attachment; filename=" + file.getName());
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(file));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
throw new FileDownloadException("文件流转换异常");
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
}*