Springboot文件下载

2020-02-28  本文已影响0人  一曲畔上

以Springboot的方式文件下载,有如下两个示例:

方式一

@RequestMapping(value = {"/dl"},  method = {RequestMethod.GET})
public ResponseEntity<ByteArrayResource> downloadFile1() throws IOException {   
    Path path = Paths.get("C:/文件.xlsx");
    byte[] data = Files.readAllBytes(path);
    ByteArrayResource resource = new ByteArrayResource(data);
    
    return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + URLEncoder.encode(path.getFileName().toString(), "UTF-8"))
                .contentType(MediaType.APPLICATION_OCTET_STREAM).contentLength(data.length)
                .body(resource);
}

方式二

@RequestMapping(value = {"/dl"}, method = {RequestMethod.GET})
public ResponseEntity<InputStreamResource> downloadFile1() throws IOException {

    File file = new File("C:/文件.xlsx");
    InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
    
    return ResponseEntity.ok()
           .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"))
           .contentType(MediaType.APPLICATION_OCTET_STREAM).contentLength(file.length())
           .body(resource);
}
上一篇 下一篇

猜你喜欢

热点阅读