美文网首页
spring下载文件的正确做法

spring下载文件的正确做法

作者: 江江的大猪 | 来源:发表于2020-04-19 01:56 被阅读0次
  • 不用设置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);
    }

相关文章

网友评论

      本文标题:spring下载文件的正确做法

      本文链接:https://www.haomeiwen.com/subject/wdyfbhtx.html