@GetMapping("/download")
public ResponseEntity<byte[]> download(HttpServletRequest request) throws Exception {
ClassPathResource resource = new ClassPathResource("文件");
byte[] body = FileUtil.readFile(resource.getAbsolutePath());
HttpHeaders headers = new HttpHeaders();
String fileName = resource.getName();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
// 判断浏览器类型,火狐的浏览器编码为 iso-8859-1
if (request.getHeader("USER-AGENT").toLowerCase().contains("firefox")) {
fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
headers.setContentDispositionFormData("attachment", fileName);
} else {
// 其他浏览器类型可以用一下代码方式解决中文文件名乱码问题
headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, "UTF-8"));
}
ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, HttpStatus.OK);
return entity;
}
public byte[] readFile(String fileName) {
byte[] body = null;
File file = new File(filePath+fileName);
InputStream is = null;
try {
is = new FileInputStream(file);
body = new byte[is.available()];
is.read(body);
return body;
} catch (Exception e) {
e.printStackTrace();
return "文件下载失败".getBytes();
}finally {
try {
if(is != null) {
is.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}