欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java使用FTP实现文件上传/下载

程序员文章站 2022-04-15 18:03:37
文章目录概要步骤概要项目中会用到从FTP上读取大量图片。步骤pom.xml文件commons-netcommons-net3.5...

文章目录

概要

项目中会用到从FTP上读取大量图片。

步骤

  1. pom.xml文件
	<!--FTP包-->
	<dependency>
		<groupId>commons-net</groupId>
		<artifactId>commons-net</artifactId>
		<version>3.5</version>
	</dependency>
	<!--日志包-->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.9</version>
		</dependency>
  1. 定义ftp账号配置文件,ftp.yml
ftpConfig:
  host: 192.168.xxx.xxx
  port: 21
  username: xxxxx
  password: xxxxx
  1. ftp配置类,FtpConfig.java
@Component
public class FtpConfig implements Serializable {
    private static final long serialVersionUID = 1L;
    private String host;
    private int port;
    private String username;
    private String password;
    public FtpConfig() {}
    public FtpConfig(String host, int port, String userName, String password) {
        this.host = host;
        this.port = port;
        this.username = userName;
        this.password = password;
    }
    // 省略get/set
  1. 工厂类,用于创建不同的ftp配置,FtpConfigUtil.java
@Component
public class FtpConfigUtil {
    @Value("${ftpConfig.host}")
    private String ftpHost;
    @Value("${ftpConfig.port}")
    private int ftpPort;
    @Value("${ftpConfig.username}")
    private String ftpUsername;
    @Value("${ftpConfig.password}")
    private String ftpPassword;
    public FtpConfig createFtpConfig() {
        return new FtpConfig(ftpHost, ftpPort, ftpUsername, ftpPassword);
    }
    public String getFtpHost() {
        return ftpHost;
    }
    public int getFtpPort() {
        return ftpPort;
    }
    public String getFtpUsername() {
        return ftpUsername;
    }
    public String getFtpPassword() {
        return ftpPassword;
    }
}
  1. 获取FTP配置接口
    FtpController.java
@RestController
@RequestMapping("/ftp")
@Api("图片ftp相关api")
public class FtpController extends BaseController {
    private static Logger logger = Logger.getLogger(FtpController.class);
    @Autowired
    private FtpStorage ftpStorage;
    @Autowired
    private FtpConfigUtil ftpConfigUtil;
    /**
     * 获取FTP的配置.
     * @return FTP的配置
     */
    @ApiOperation(value = "获取上传文件的FTP路径.")
    @RequestMapping(value = "/getFtpConfig", method = RequestMethod.GET)
    public CommonOutputResult getFtpConfigController() {
        String ftpFilePath = "xxx/xxx";//根据业务需求定制
        ftpStorage.createFolder(ftpFilePath);
        FtpDatasetDto config = new FtpDatasetDto(ftpConfigUtil.getFtpUsername(), ftpConfigUtil.getFtpPassword(),
                ftpConfigUtil.getFtpPort(), ftpFilePath);
        return newSuccessDataInstance(config);
    }
}
// CommonOutputResult 是自己封装的一个结果类,文末下载链接自取
// FtpDatasetDto 封装的返回结果类,属性有String userName,String password,int port,String uploadPath,构造函数,get/set方法

FTP存储实现类,FtpStorage.java

package com.util.storage.impl;
import com.util.ftp.FtpClient;
import com.util.ftp.FtpConfigUtil;
import com.util.storage.Storage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
@Component
public class FtpStorage implements Storage {
    @Autowired
    private FtpConfigUtil ftpConfigUtil;
    @Value("${storage.ftp.prefix}")
    private String prefix;
    /**
     * 创建文件夹.
     * @param folderPath 文件夹路径
     */
    @Override
    public boolean createFolder(String folderPath) {
        FtpClient ftpClient = new FtpClient(ftpConfigUtil.createFtpConfig());
        return ftpClient.createAbsoluteDir(prefix + folderPath);
    }
    /**
     * 删除文件夹.
     * @param folderPath 文件夹路径
     */
    @Override
    public boolean deleteFolder(String folderPath) {
        FtpClient ftpClient = new FtpClient(ftpConfigUtil.createFtpConfig());
        return ftpClient.deleteDir(prefix + folderPath);
    }
    /**
     * 上传文件.
     * @param localFilePath 本地文件路径
     * @param destFolderPath 目标文件夹路径
     * @param destFileName 目标文件名称
     * @return boolean
     */
    @Override
    public boolean putObject(String localFilePath, String destFolderPath, String destFileName) {
        FtpClient ftpClient = new FtpClient(ftpConfigUtil.createFtpConfig());
        return ftpClient.uploadFile(prefix + destFolderPath, destFileName, localFilePath);
    }
    /**
     * 上传文件.
     * @param multipartFile 文件
     * @param destFolderPath 目标文件夹路径
     * @param destFileName 目标文件名称
     */
    @Override
    public boolean putObject(MultipartFile multipartFile, String destFolderPath,
                             String destFileName) throws IOException {
        FtpClient ftpClient = new FtpClient(ftpConfigUtil.createFtpConfig());
        return ftpClient.uploadFile(prefix + destFolderPath, destFileName, multipartFile);
    }
    /**
     * 获取文件.
     * @param folderPath 文件夹路径
     * @param fileName 文件名称
     * @return FileInputStream
     */
    @Override
    public InputStream getObject(String folderPath, String fileName) throws IOException {
        FtpClient ftpClient = new FtpClient(ftpConfigUtil.createFtpConfig());
        byte[] bytes = ftpClient.downloadFile(prefix + folderPath, fileName);
        return new ByteArrayInputStream(bytes);
    }
    /**
     * 删除文件.
     * @param folderPath 文件夹路径
     * @param fileName 文件名称
     */
    @Override
    public boolean deleteObject(String folderPath, String fileName) {
        FtpClient ftpClient = new FtpClient(ftpConfigUtil.createFtpConfig());
        return ftpClient.deleteFile(prefix + folderPath, fileName);
    }
    /**
     * 复制文件.
     * @param sourceFolderPath 源文件夹路径
     * @param sourceFileName 源文件名称
     * @param targetFolderPath 目标文件夹路径
     * @param targetFileName 目标文件名称
     */
    @Override
    public boolean copyObject(String sourceFolderPath, String sourceFileName,
                              String targetFolderPath, String targetFileName) throws IOException {
        FtpClient ftpClient = new FtpClient(ftpConfigUtil.createFtpConfig());
        return ftpClient.copyFile(prefix + sourceFolderPath + sourceFileName,
                prefix + targetFolderPath, targetFileName);
    }
    /**
     * 返回FTP目录下的文件列表
     * @param ftpDirectory
     */
    @Override
    public List<String> getFileNameList(String ftpDirectory) {
        List<String> list = null;
        FtpClient ftpClient = new FtpClient(ftpConfigUtil.createFtpConfig());
        list = ftpClient.getFileList(prefix + ftpDirectory, ftpClient);
        return list;
    }
}

FtpClient.java省略(核心类),(完整的工具类文末下载链接自取)

@Component
public class FtpClient {
	 private static final Logger LOGGER = Logger.getLogger(FtpClient.class);
    private static final int BUF_SIZE = 1024 * 2;
    private static final String CONTROL_ENCODING_UTF8 = "UTF-8";
    private static final int INVALID_CODE = 550;
    private FTPClient mFtpClient;
    private FtpConfig mConfig;
    private boolean connect() {
        if (mFtpClient.isConnected()) {
            return true;
        }
        try {
            mFtpClient.connect(mConfig.getHost(), mConfig.getPort());
            mFtpClient.login(mConfig.getUsername(), mConfig.getPassword());
            int replyCode = mFtpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                mFtpClient.disconnect();
                LOGGER.info("FTP connect failed.");
                return false;
            }
        } catch (IOException exception) {
            exception.printStackTrace();
            return false;
        }
        return true;
    }

    public void disconnect() {
        logoutFtp();
        disconnectFtp();
    }
    // .......
}
  1. 上面提到两个类的下载地址:https://download.csdn.net/download/weixin_45044097/13107142

本文地址:https://blog.csdn.net/weixin_45044097/article/details/109637761