使用FTPClient封装FtpUtil

1. 新增POM依赖

<!--文件上传-->
<dependency>
    <groupId>commons-fileupload</groupId>       
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>

<!--FTPClient-->
<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.1</version>
</dependency>

2. 封装代码

2.1 FtpUtil

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

@Slf4j
public class FtpUtil {

    private String host;
    private Integer port;
    private String username;
    private String password;
    private FTPClient ftpClient;

    private FtpUtil() {
        this.host = "127.0.0.1";
        this.port = 21;
        this.username = "root";
        this.password = "root";
    }

    /**
     * 上传图片到FTP服务器
     *
     * @param file
     * @return
     */
    public static boolean uploadImg(File file) {
        return new FtpUtil().uploadFile("/images", file);
    }

    /**
     * 删除FTP服务器上的单个图片
     *
     * @param imgName
     * @return
     */
    public static boolean deleteImg(String imgName) {
        return new FtpUtil().deleteFile("/images", imgName);
    }

    /**
     * 删除多个文件
     *
     * @param imgNames
     */
    public static void deleteImgs(List<String> imgNames) {
        new FtpUtil().deleteFiles("/images", imgNames);
    }

    /**
     * 上传文件到FTP服务器
     *
     * @param path
     * @param file
     * @return
     */
    private boolean uploadFile(String path, File file) {
        try {
            if (connect()) {
                FileInputStream fileInputStream;
                ftpClient.changeWorkingDirectory(path);     // 切换工作目录
                ftpClient.setBufferSize(2048);
                ftpClient.setControlEncoding("UTF-8");
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);      //设置文件格式为二进制格式
                ftpClient.enterLocalPassiveMode();
                fileInputStream = new FileInputStream(file);
                ftpClient.storeFile(file.getName(), fileInputStream);
                ftpClient.disconnect();
                fileInputStream.close();
                log.info("文件 {} 上传成功", file.getName());
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除FTP服务器中的文件
     *
     * @param path
     * @param fileName
     * @return
     */
    private boolean deleteFile(String path, String fileName) {
        boolean uploadResult = false;
        try {
            if (connect()) {
                ftpClient.changeWorkingDirectory(path);
                if (ftpClient.deleteFile(fileName)) {
                    log.info("文件 {} 删除成功", fileName);
                    uploadResult = true;
                } else {
                    log.info("文件 {} 删除失败", fileName);
                }
                ftpClient.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return uploadResult;
    }

    /**
     * 删除多个文件
     * @param path
     * @param imgNames
     * @return
     */
    private Integer deleteFiles(String path, List<String> imgNames) {
        int count = 0;
        try {
            if (connect()) {
                ftpClient.changeWorkingDirectory(path);
                for (String s : imgNames) {
                    if (ftpClient.deleteFile(s)) {
                        log.info("文件 {} 删除成功", s);
                        count++;
                    } else {
                        log.info("文件 {} 删除失败", s);
                    }
                }
                log.info("共删除 {} 张图片", count);
                ftpClient.disconnect();
            }
        } catch (IOException e) {
            log.error("连接FTP服务器失败");
        }
        return count;
    }


    /**
     * 连接到FTP服务器
     *
     * @return
     */
    private boolean connect() {
        boolean connectResult = false;
        try {
            ftpClient = new FTPClient();
            ftpClient.connect(host, port);
            connectResult = ftpClient.login(username, password);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return connectResult;
    }

}

2.2 Controller测试

@PostMapping("/upload/image")
    public String upload(@RequestParam("file") MultipartFile file) throws IOException {
        // 现将文件暂存到该路径下
        String sysPath = "./src/main/resources/static/images/";
        String fileName = file.getOriginalFilename();
        File image = new File(sysPath + fileName);
        FileUtils.copyInputStreamToFile(file.getInputStream(), image);
        boolean result = FtpUtil.uploadImg(image);

        // 删除项目中暂存的图片文件
        image.delete();

        if (result) {
            return "文件上传成功";
        }
        return "文件上传失败";
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值