- 不用设置content-length,会自动设置
- 设置ContentDisposition,浏览器下载时的名字,中文的话不用url编码也不会乱码,ContentDisposition会根据传入的Charsets.UTF_8自动编码
@RequestMapping("home")
public ResponseEntity<byte[]> test() throws IOException {
byte[] bytes = Files.asByteSource(new File("/Users/lfz/favicon.ico")).read();
HttpHeaders headers=new HttpHeaders();
//设置MIME类型
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDisposition(ContentDisposition.builder("attachment").filename("汉字.ico", Charsets.UTF_8).build());
return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
}
// 原封不动返回上传的文件
@PostMapping("/upload")
public ResponseEntity<byte[]> upload(MultipartFile file) throws IOException {
if (file.isEmpty()) {
return ResponseEntity.ok().build();
}
HttpHeaders headers=new HttpHeaders();
//设置MIME类型
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDisposition(ContentDisposition.builder("attachment").filename(StringUtils.isEmpty(file.getOriginalFilename()) ? "下载文件" : file.getOriginalFilename(), StandardCharsets.UTF_8).build());
return new ResponseEntity<>(file.getBytes(), headers, HttpStatus.OK);
}
网友评论