- 不用設置content-length,會自動設置
- 設置ContentDisposition,瀏覽器下載時的名字,中文的話不用url編碼也不會亂碼,ContentDisposition會根據(jù)傳入的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);
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。