spring下载文件的正确做法

2020-04-19  本文已影响0人  江江的大猪
    @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);
    }
上一篇下一篇

猜你喜欢

热点阅读