SpringBoot+FTP下载文件,单文件直接下载,多文件进行打包zip下载

直接调用downloadFiles方法即可

package com.demo.utils;

import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * FTP文件下载器
 *
 * @author lhj
 * @date 2024/04/15
 */
public class FtpFileDownloader {


    /**
     * 下载FTP文件
     *
     * @param filePaths 文件路径
     * @return 响应实体<?>
     * @throws IOException ioexception
     */
    @PostMapping("/downloadFtpFiles")
    public ResponseEntity<?> downloadFtpFiles(@RequestParam("filePaths") List<String> filePaths) throws IOException {
        // 实现下载逻辑...
        return null;
    }

    /**
     * 下载文件。该方法支持单个文件和多个文件的下载。当下载多个文件时,它们会被打包成一个zip文件进行下载。
     *
     * @param filePaths 文件路径列表。可以包含一个或多个文件路径。
     * @param response  响应对象,用于设置下载响应信息和输出文件内容。
     * @throws IOException 当发生IO异常时抛出。
     */
    public void downloadFiles(List<String> filePaths, HttpServletResponse response) throws IOException {
        FTPClient ftpClient = new FTPClient();
        try {
            // 连接到FTP服务器
            ftpClient.login("your_username", "your_password");

            // 判断是否需要打包下载
            if (filePaths.size() > 1) {
                // 设置响应类型为zip文件
                response.setContentType("application/zip");
                // 设置附件下载头,并指定下载文件名
                response.setHeader("Content-Disposition", "attachment; filename=\"files.zip\"");

                // 创建Zip输出流
                ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
                for (String filePath : filePaths) {
                    // 获取FTP文件信息
                    FTPFile ftpFile = ftpClient.listFiles(filePath)[0];
                    if (ftpFile.isFile()) {
                        // 获取文件输入流
                        InputStream inputStream = ftpClient.retrieveFileStream(filePath);
                        if (inputStream == null) {
                            continue; // 文件不存在或读取失败,跳过当前文件
                        }

                        // 添加文件到Zip输出流
                        ZipEntry zipEntry = new ZipEntry(getFileNameFromPath(filePath));
                        zos.putNextEntry(zipEntry);

                        // 将文件内容写入Zip输出流
                        IOUtils.copy(inputStream, zos);
                        zos.closeEntry();
                        // 关闭文件输入流
                        inputStream.close();
                        // 必须加这行,不然第二次循环路径不对  调用此方法来尝试完成未完成的命令。它主要用于恢复连接和确保数据传输的完整性。
                        ftpClient.completePendingCommand();
                    }
                }
                // 结束Zip输出流并关闭
                zos.finish();
                zos.close();
            } else if (filePaths.size() == 1) {
                // 单个文件下载逻辑
                String singleFilePath = filePaths.get(0);
                FTPFile ftpFile = ftpClient.listFiles(singleFilePath)[0];
                if (ftpFile.isFile()) {
                    // 设置响应类型为文件类型
                    response.setContentType(getContentTypeFromFileName(singleFilePath));
                    // 设置附件下载头,并指定下载文件名
                    response.setHeader("Content-Disposition", "attachment; filename=\"" + getFileNameFromPath(singleFilePath) + "\"");
                    // 创建输出流
                    OutputStream outputStream = response.getOutputStream();
                    // 获取文件输入流
                    InputStream inputStream = ftpClient.retrieveFileStream(singleFilePath);
                    // 将文件内容写入输出流
                    IOUtils.copy(inputStream, outputStream);
                    // 关闭输入输出流
                    inputStream.close();
                    outputStream.flush();
                }
            }
        } catch (IOException e) {
            // 抛出IO异常
            throw e;
        } finally {
            // 断开FTP连接并登出
            ftpClient.logout();
            ftpClient.disconnect();
        }
    }


    /**
     * 从路径获取文件名
     *
     * @param path 路径
     * @return 字符串
     */
    private String getFileNameFromPath(String path) {
        return path.substring(path.lastIndexOf("/") + 1);
    }

    /**
     * 从文件名获取内容类型
     *
     * @param fileName 文件名称
     * @return 字符串
     */
    private String getContentTypeFromFileName(String fileName) {
        // 根据文件扩展名返回contentType,这里只是一个简单示例,实际项目中可能需要更完善的映射规则
        return fileName.endsWith(".pdf") ? "application/pdf" : "application/octet-stream";
    }
}

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringBoot中,可以使用FTP协议下载文件。首先,你需要引入相关的包并进行配置。具体步骤如下: 1. 引入依赖:在你的项目的pom.xml文件中添加FTP客户端的依赖。 2. 配置连接参数:创建一个配置类,例如FtpInteranceEntity,使用@ConfigurationProperties注解来指定配置文件的前缀,并使用@PropertySource注解指定配置文件的路径。在配置类中,定义FTP服务器的地址、端口号、用户名、密码、上传的根目录等参数。 3. 创建接口服务:创建一个接口服务类,例如FtpService,使用@Autowired注解注入FtpInteranceEntity配置类。在接口服务类中,可以编写下载文件的方法。通过使用Apache Commons Net库中的FTPClient类,可以连接到FTP服务器并下载文件。 下面是一个简的示例代码: ```java @Service public class FtpService { @Autowired private FtpInteranceEntity ftpConfig; public void downloadFile(String remoteFilePath, String localFilePath) { FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(ftpConfig.getHost(), Integer.parseInt(ftpConfig.getPort())); ftpClient.login(ftpConfig.getUsername(), ftpConfig.getPassword()); File localFile = new File(localFilePath); OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(localFile)); ftpClient.retrieveFile(remoteFilePath, outputStream); outputStream.close(); ftpClient.logout(); System.out.println("文件下载成功!"); } catch (IOException e) { System.out.println("文件下载失败:" + e.getMessage()); } } } ``` 在上述代码中,我们通过FTPClient类的connect方法连接到FTP服务器,并使用login方法进行登录。然后,我们创建一个本地文件,并通过retrieveFile方法从服务器下载文件。最后,我们关闭输出流和FTP连接,并打印出下载成功的消息。 请注意,你需要根据实际情况修改配置类和接口服务类的代码,以适应你的具体需求和环境。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [SpringBoot+ftp 实现文件的上传、下载与删除](https://blog.csdn.net/u014295903/article/details/114629907)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [基于Python实现FTP文件上传与下载操作(FTP&SFTP协议)](https://download.csdn.net/download/wjianwei666/88279227)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值