Spring Boot文件下载

一、Spring Boot下载文件到本地硬盘

在Spring Boot中,我们可以通过以下代码实现将一个文件下载到本地硬盘中:

@GetMapping("/download")
public ResponseEntity<FileSystemResource> download(HttpServletRequest request) throws IOException {
    String fileName = "file.txt";
    String filePath = "path/to/file/" + fileName;
    FileSystemResource fileSystemResource = new FileSystemResource(filePath);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
    headers.add("Content-Disposition", "attachment; filename=" + fileName);
    headers.add("Pragma", "no-cache");
    headers.add("Expires", "0");
    return ResponseEntity.ok().headers(headers).contentLength(fileSystemResource.contentLength())
        .contentType(MediaType.parseMediaType("application/octet-stream")).body(fileSystemResource);
}

我们可以从请求中得到文件名,然后通过FileSystemResource获取文件的真实路径。

使用ResponseEntity将文件的内容输出到响应体中,实现文件下载到本地硬盘。同时通过添加相关的响应头信息来告诉浏览器将这个响应当做一个文件下载。

二、Spring Boot FTP下载文件

如果要实现从FTP服务器下载文件,我们可以使用Apache Commons Net库

首先添加maven依赖:

<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.6</version>
</dependency>

然后通过以下代码实现从FTP服务器下载文件:

@GetMapping("/ftpdownload")
public String ftpDownload(HttpServletRequest request) throws IOException {
    String server = "FTP服务器地址";
    int port = 21;
    String user = "用户名";
    String password = "密码";
    String remoteFilePath = "远程文件路径";
    String localFilePath = "本地文件路径";
    FTPClient ftpClient = new FTPClient();
    ftpClient.connect(server, port);
    ftpClient.login(user, password);
    InputStream inputStream = ftpClient.retrieveFileStream(remoteFilePath);
    OutputStream outputStream = new FileOutputStream(localFilePath);
    byte[] bytesArray = new byte[4096];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(bytesArray)) != -1) {
        outputStream.write(bytesArray, 0, bytesRead);
    }
    boolean success = ftpClient.completePendingCommand();
    inputStream.close();
    outputStream.close();
    ftpClient.logout();
    ftpClient.disconnect();
    if (success) {
        return "下载成功";
    } else {
        return "下载失败";
    }
}

使用FTPClient连接到FTP服务器,并通过retrieveFileStream方法获取文件的输入流。

然后使用FileOutputStream将输入流写入到本地文件中。

三、Spring Boot文件上传下载功能

我们可以通过Spring Boot的MultipartFile来实现文件的上传,而下载则可以参考第一部分的做法。

以下代码实现了文件上传和下载的完整功能:

@GetMapping("/download")
public ResponseEntity<FileSystemResource> download(HttpServletRequest request) throws IOException {
    ...
}

@PostMapping("/upload")
public String upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {
    String fileName = file.getOriginalFilename();
    String filePath = "path/to/file/" + fileName;
    file.transferTo(new File(filePath));
    return "上传成功";
}

文件上传使用@RequestParam注解获取文件,然后通过transferTo方法将文件写入到指定的路径中。

文件下载使用和第一部分中的代码一样的方式。

四、Spring Boot浏览器下载文件

如果需要将文件直接显示在浏览器中,而不是下载到本地硬盘,我们可以对第一部分中的代码进行修改:

@GetMapping("/display")
public ResponseEntity<FileSystemResource> display(HttpServletRequest request) throws IOException {
    String fileName = "file.txt";
    String filePath = "path/to/file/" + fileName;
    FileSystemResource fileSystemResource = new FileSystemResource(filePath);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
    headers.add("Content-Disposition", "inline; filename=" + fileName);
    headers.add("Pragma", "no-cache");
    headers.add("Expires", "0");
    return ResponseEntity.ok().headers(headers).contentLength(fileSystemResource.contentLength())
        .contentType(MediaType.parseMediaType("application/octet-stream")).body(fileSystemResource);
}

将Content-Disposition响应头的attachment改为inline即可直接在浏览器中显示文件内容。

五、Spring Boot下载文件到本地目录

如果需要将文件下载到指定的本地目录中,我们可以通过以下代码实现:

@GetMapping("/folder")
public void folder(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String fileName = "file.txt";
    String filePath = "path/to/file/" + fileName;
    File file = new File(filePath);
    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
    response.setContentType("application/octet-stream");
    response.setContentLength((int) file.length());
    FileInputStream inputStream = new FileInputStream(file);
    OutputStream outputStream = response.getOutputStream();
    byte[] bytesArray = new byte[4096];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(bytesArray)) != -1) {
        outputStream.write(bytesArray, 0, bytesRead);
    }
    inputStream.close();
    outputStream.close();
}

在这里,我们使用HttpServletResponse的getOutputStream方法获取输出流,然后将文件的内容写入到输出流中。

六、Spring Boot批量下载文件

最后,如果需要实现批量下载文件的功能,可以通过以下代码实现:

@GetMapping("/batch")
public void batch(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String[] fileNames = {"file1.txt", "file2.txt"};
    ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
    for (String fileName : fileNames) {
        String filePath = "path/to/file/" + fileName;
        File file = new File(filePath);
        FileInputStream inputStream = new FileInputStream(file);
        ZipEntry zipEntry = new ZipEntry(fileName);
        zipOut.putNextEntry(zipEntry);
        byte[] bytesArray = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = inputStream.read(bytesArray)) != -1) {
            zipOut.write(bytesArray, 0, bytesRead);
        }
        inputStream.close();
    }
    zipOut.finish();
}

在这里,我们首先将多个文件名存放在一个数组中,然后使用ZipOutputStream将这些文件压缩为一个压缩包。

在输出响应体时,使用response的getOutputStream方法获取输出流并将压缩包写入到流中。

总结

本文详细介绍了在Spring Boot中实现文件下载的多个方面,包括下载到本地硬盘中、从FTP服务器下载文件、文件上传下载功能、浏览器下载文件、下载文件到本地目录和批量下载文件。

通过这些方法,我们可以实现非常灵活、实用的文件下载功能,便于我们在开发中实现各种各样的需求。

原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/248504.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
小蓝小蓝
上一篇 2024-12-12 13:27
下一篇 2024-12-12 13:27

相关推荐

  • vue下载无后缀名的文件被加上后缀.txt,有后缀名的文件下载正常问题的解决

    本文旨在解决vue下载无后缀名的文件被加上后缀.txt,有后缀名的文件下载正常的问题,提供完整的代码示例供参考。 一、分析问题 首先,需了解vue中下载文件的情况。一般情况下,我们…

    编程 2025-04-29
  • 如何在Java中拼接OBJ格式的文件并生成完整的图像

    OBJ格式是一种用于表示3D对象的标准格式,通常由一组顶点、面和纹理映射坐标组成。在本文中,我们将讨论如何将多个OBJ文件拼接在一起,生成一个完整的3D模型。 一、读取OBJ文件 …

    编程 2025-04-29
  • Python中读入csv文件数据的方法用法介绍

    csv是一种常见的数据格式,通常用于存储小型数据集。Python作为一种广泛流行的编程语言,内置了许多操作csv文件的库。本文将从多个方面详细介绍Python读入csv文件的方法。…

    编程 2025-04-29
  • Python程序文件的拓展

    Python是一门功能丰富、易于学习、可读性高的编程语言。Python程序文件通常以.py为文件拓展名,被广泛应用于各种领域,包括Web开发、机器学习、科学计算等。为了更好地发挥P…

    编程 2025-04-29
  • 为什么用cmd运行Java时需要在文件内打开cmd为中心

    在Java开发中,我们经常会使用cmd在命令行窗口运行程序。然而,有时候我们会发现,在运行Java程序时,需要在文件内打开cmd为中心,这让很多开发者感到疑惑,那么,为什么会出现这…

    编程 2025-04-29
  • Python将矩阵存为CSV文件

    CSV文件是一种通用的文件格式,在统计学和计算机科学中非常常见,一些数据分析工具如Microsoft Excel,Google Sheets等都支持读取CSV文件。Python内置…

    编程 2025-04-29
  • Python zipfile解压文件乱码处理

    本文主要介绍如何在Python中使用zipfile进行文件解压的处理,同时详细讨论在解压文件时可能出现的乱码问题的各种解决办法。 一、zipfile解压文件乱码问题的根本原因 在P…

    编程 2025-04-29
  • Spring Boot 集成 Jacoco

    本文将从以下几个方面介绍如何在 Spring Boot 中集成 Jacoco:1、Jacoco 概述;2、Spring Boot 集成 Jacoco 的配置;3、生成 Jacoco…

    编程 2025-04-29
  • Python如何导入py文件

    Python是一种开源的高级编程语言,因其易学易用和强大的生态系统而备受青睐。Python的import语句可以帮助用户将一个模块中的代码导入到另一个模块中,从而实现代码的重用。本…

    编程 2025-04-29
  • Python合并多个相同表头文件

    对于需要合并多个相同表头文件的情况,我们可以使用Python来实现快速的合并。 一、读取CSV文件 使用Python中的csv库读取CSV文件。 import csv with o…

    编程 2025-04-29

发表回复

登录后才能评论