无名阁,只为技术而生。流水不争先,争的是滔滔不绝。

(spring boot 下载文件) SpringBoot实现文件下载的四种方式 Spring Boot实现文件下载主要方法 全网首发(图文详解1)

前沿技术 Micheal 3个月前 (06-12) 54次浏览 已收录 扫描二维码

(spring boot 下载文件) SpringBoot实现文件下载的四种方式

Spring Boot实现文件下载主要有以下四种方式,我会逐一解释,并给出实现的代码示例及配置:

1. 基于ServletResponse的方式

这种方式主要通过HttpServletResponse对象来实现文件的下载。

@GetMapping("/download1")
public void downloadFile1(HttpServletResponse response) {
    // 文件路径
    String filePath = "/path/to/your/file.txt";
    File file = new File(filePath);
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
    // 实现文件下载
    try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        OutputStream os = response.getOutputStream()) {
        byte[] buffer = new byte[1024];
        int len;
        while ((len = bis.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

2. 基于Spring的FileSystemResource

如果你需要更简洁的方式,Spring提供了FileSystemResource来简化文件下载。

@GetMapping("/download2")
public ResponseEntity<FileSystemResource> downloadFile2() {
    // 文件路径
    String filePath = "/path/to/your/file.txt";
    File file = new File(filePath);

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.parseMediaType("application/octet-stream"))
            .body(new FileSystemResource(file));
}

3. 通过Spring MVC的ResponseEntity<byte[]>返回

这种方式通过将文件内容读入到byte数组中,然后通过ResponseEntity返回。

@GetMapping("/download3")
public ResponseEntity<byte[]> downloadFile3() throws IOException {
    // 文件路径
    String filePath = "/path/to/your/file.txt";
    File file = new File(filePath);
    byte[] fileContent = Files.readAllBytes(file.toPath());

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

    return ResponseEntity.ok()
            .headers(headers)
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(fileContent);
}

4. StreamingResponseBody接口

当文件非常大时,使用StreamingResponseBody可以边读边下载,防止内存溢出。

@GetMapping("/download4")
public ResponseEntity<StreamingResponseBody> downloadFile4() {
    // 文件路径
    String filePath = "/path/to/your/file.txt";
    File file = new File(filePath);

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

    StreamingResponseBody responseBody = outputStream -> {
        try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    };

    return ResponseEntity.ok()
            .headers(headers)
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(responseBody);
}

这些方式各有特点,可以根据实际需求选择合适的方式进行文件下载实现。
(html target) html中的target属性详解 HTML target 属性介绍 全网首发(图文详解1)
(热血传奇道士48练级攻略) 热血传奇怎么升级比较快 快速升级攻略 快速升级攻略:热血传奇玩家的必读指南 全网首发(图文详解1)

喜欢 (0)
[]
分享 (0)
关于作者:
流水不争先,争的是滔滔不绝