java Spring boot 引入FTP功能

1,maven 引入

FTP maven 引入

  1. 配置文件
    FTP配置

3.代码实现

FtpProperties

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

 */
@Data
@Component
@ConfigurationProperties(prefix = "ftp")
public class FtpProperties {
    /**
     * ftp服务器的地址
     */
    private String host;
    /**
     * ftp服务器的端口号(连接端口号)
     */
    private String port;
    /**
     * ftp的用户名
     */
    private String username;
    /**
     * ftp的密码
     */
    private String password;
    /**
     * ftp上传的根目录
     */
    private String basePath;
    /**
     * 回显地址
     */
    private String httpPath;
}

FtpService

import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;


public interface FtpService {
    /**
     * 上传文件到ftp
     * @param multipartFile
     * @return
     */
    public boolean uploadMultipartFile(MultipartFile multipartFile, String filePath);

    /**
     * 上传内容(文件形式)到ftp
     * @param content 文件内容
     * @param fileName 文件名称
     * @param filePath ftp路径
     * @return
     */
    public boolean uploadFileWithContent(String content, String fileName,String filePath);

    /**
     * 下载ftp文件,直接转到输出流
     * @param fileName
     * @param ftpFilePath
     * @param response
     */
    public void downloadFileToFtp(String fileName, String ftpFilePath, HttpServletResponse response);

    /**
     * 删除ftp文件
     * @param ftpFilePath ftp下文件路径,根目录开始
     * @return
     */
    boolean deleteFileToFtp(String ftpFilePath);
}

实现类 FtpServiceImpl

import cn.hutool.core.util.StrUtil;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Objects;

@Service
public class FtpServiceImpl implements FtpService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private FtpProperties ftpProperties;


    @Override
    public boolean uploadMultipartFile(MultipartFile multipartFile,String filePath) {
        if (multipartFile == null || multipartFile.isEmpty()) {
            logger.error("上传文件内容为空!");
            return false;
        }
        try {
            String path = (Objects.nonNull(filePath) ? ftpProperties.getBasePath()+"/"+ filePath.trim() : ftpProperties.getBasePath());
            return uploadFileToFtp(multipartFile.getInputStream(), multipartFile.getOriginalFilename(), path);
        } catch (Exception e) {
            logger.error("文件上传失败:", e);
            return false;
        }
    }

    @Override
    public boolean uploadFileWithContent(String content,String fileName, String filePath) {
        try {
            String path = (Objects.nonNull(filePath) ? ftpProperties.getBasePath()+"/"+ filePath.trim() : ftpProperties.getBasePath());
            return uploadFileToFtp(new ByteArrayInputStream(content.getBytes()),fileName, path);
        } catch (Exception e) {
            logger.error("文件上传失败:", e);
            return false;
        }
    }

    public Boolean uploadFileToFtp(InputStream inputStream , String fileName, String filePath) {
        logger.info("调用文件上传接口,文件名称:"+fileName);
        // 定义保存结果
        boolean iaOk = false;
        // 初始化连接
        FTPClient ftp = connectFtpServer();
        if (ftp != null) {
            try {
                // 设置文件传输模式为二进制,可以保证传输的内容不会被改变
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
                ftp.enterLocalPassiveMode();    //注:上传文件都为0字节,设置为被动模式即可
                // 跳转到指定路径,逐级跳转,不存在的话就创建再进入
                toPathOrCreateDir(ftp, filePath);
                // 上传文件 参数:上传后的文件名,输入流,,返回Boolean类型,上传成功返回true
                iaOk = ftp.storeFile(fileName, inputStream);
                // 关闭输入流
                inputStream.close();
                // 退出ftp
                ftp.logout();
            } catch (IOException e) {
                logger.error(e.toString());
            } finally {
                if (ftp.isConnected()) {
                    try {
                        // 断开ftp的连接
                        ftp.disconnect();
                    } catch (IOException ioe) {
                        logger.error(ioe.toString());
                    }
                }
            }
        }
        return iaOk;
    }

    @Override
    public void downloadFileToFtp(String fileName, String ftpFilePath, HttpServletResponse response) {
        FTPClient ftpClient = connectFtpServer();
        try {
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            // 设置文件ContentType类型,这样设置,会自动判断下载文件类型
            response.setContentType("application/x-msdownload");
            // 设置文件头:最后一个参数是设置下载的文件名并编码为UTF-8
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
            InputStream is = ftpClient.retrieveFileStream(ftpFilePath);
            BufferedInputStream bis = new BufferedInputStream(is);
            OutputStream out = response.getOutputStream();
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = bis.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            out.flush();
            out.close();

            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            ftpClient.logout();
        } catch (Exception e) {
            logger.error("FTP文件下载失败:", e);
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                    logger.error(ioe.toString());
                }
            }
        }
    }

    @Override
    public boolean deleteFileToFtp(String ftpFilePath) {
        FTPClient ftp = connectFtpServer();
        try {
            return ftp.deleteFile(ftpFilePath);
        } catch (Exception e) {
            logger.error("FTP文件删除失败:{}", e);
            return false;
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    logger.error(ioe.toString());
                }
            }
        }
    }

    private FTPClient connectFtpServer() {
        // 创建FTPClient对象(对于连接ftp服务器,以及上传和上传都必须要用到一个对象)
        logger.info("创建FTP连接");
        FTPClient ftpClient = new FTPClient();
        // 设置连接超时时间
        ftpClient.setConnectTimeout(1000 * 60);
        // 设置ftp字符集
        ftpClient.setControlEncoding("utf-8");
        // 设置被动模式,文件传输端口设置,否则文件上传不成功,也不报错
        ftpClient.enterLocalPassiveMode();
        try {
            // 定义返回的状态码
            int replyCode;
            // 连接ftp(当前项目所部署的服务器和ftp服务器之间可以相互通讯,表示连接成功)
            ftpClient.connect(ftpProperties.getHost());
            // 输入账号和密码进行登录
            ftpClient.login(ftpProperties.getUsername(), ftpProperties.getPassword());
            // 接受状态码(如果成功,返回230,如果失败返回503)
            replyCode = ftpClient.getReplyCode();
            // 根据状态码检测ftp的连接,调用isPositiveCompletion(reply)-->如果连接成功返回true,否则返回false
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                logger.info("connect ftp {} failed", ftpProperties.getHost());
                // 连接失败,断开连接
                ftpClient.disconnect();
                return null;
            }
            logger.info("replyCode:" + replyCode);
        } catch (IOException e) {
            logger.error("connect fail:" + e.toString());
            return null;
        }
        return ftpClient;
    }

    private void toPathOrCreateDir(FTPClient ftp, String filePath) throws IOException {
        String[] dirs = filePath.split("/");
        for (String dir : dirs) {
            if (StrUtil.isBlank(dir)) {
                continue;
            }

            if (!ftp.changeWorkingDirectory(dir)) {
                ftp.makeDirectory(dir);
                ftp.changeWorkingDirectory(dir);
            }
        }
    }
}

完成

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值