- 不用设置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);
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。