SpringBoot2.x使用ResponseEntity下载文件

    @GetMapping("/{id}")
    public ResponseEntity downloadFile(@PathVariable(required = false) Integer id) throws IOException {
        Image image = imageService.getById(id);
        // 设置下载文件名称,以下两种方式均可
        // String fileName = new String(image.getOldname().getBytes("UTF-8"), "iso-8859-1");
        String fileName = URLEncoder.encode(image.getOldname(), "utf-8");
        HttpHeaders httpHeaders = new HttpHeaders();
        // 通知浏览器以下载文件方式打开
        ContentDisposition contentDisposition =
                    ContentDisposition.builder("attachment").filename(fileName).build();
        headers.setContentDisposition(contentDisposition);
        // application/octet_stream设置MIME为任意二进制数据
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        // 使用apache commons-io 里边的 FileUtils工具类
        //return new ResponseEntity(FileUtils.readFileToByteArray(new File(image.getLocation())),
        //        httpHeaders, HttpStatus.OK);
        // 使用spring自带的工具类也可以 FileCopyUtils
        return new ResponseEntity(FileCopyUtils.copyToByteArray(new File(image.getLocation())),
                httpHeaders, HttpStatus.OK);
    }

 

 

你可能感兴趣的:(Spring,Boot)