FTP上传文件 名称中文乱码问题

本文使用FTPClient对FTP进行文件操作,FTPClient工具需要添加Maven依赖。

		<!-- commons-net FTP工具类-->
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.6</version>
        </dependency>

在测试文件上传过程中,发现中文名称的文件上传到FTP服务器乱码。

问题解决的思路是设置上传文件名称的编码格式为UTF-8,那么怎么设置呢?为了一劳永逸的方式解决文件上传下载均不会乱码,在FTP登录的时候设置字符编码,这样就不用担心乱码问题了。下面看代码

	public static FTPClient connectFTP(String ip, int port, String uname, String pwd) throws IOException {
        FTPClient ftpClient = new FTPClient();
        // 优先设置编码格式,避免中文乱码
        ftpClient.setAutodetectUTF8(true);
        ftpClient.setCharset(CharsetUtil.UTF_8);
        ftpClient.setControlEncoding(CharsetUtil.UTF_8.name());

        ftpClient.connect(ip, port);
        boolean login = ftpClient.login(uname, pwd);
        if (!login) {
            throw new BusinessException("ftp连接失败,请检查配置");
        }

        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.setBufferSize(DEFAULT_BUFFER_SIZE);
        return ftpClient;
    }

其中CharsetUtil使用的依赖包是netty的依赖,需要在Maven添加netty依赖。

        <!-- netty-common -->
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-common</artifactId>
            <version>4.1.77.Final</version>
        </dependency>

下面提供一个简单的FTP工具类

import xxx.xxx.xxx.BusinessException;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author 
 * @date 2022/8/2 15:53
 * @description
 */
@Slf4j
public class FtpUtils {

    private static final int DEFAULT_BUFFER_SIZE = 4096;

    /**
     * 上传文件
     *
     * @param input      输入流
     * @param uploadPath 保存路径
     * @param fileName   文件名(包含格式后缀)
     * @param ftpClient  FTP客户端连接
     * @throws IOException
     */
    public static void upload(InputStream input, String uploadPath, String fileName, FTPClient ftpClient) {
        try {
            // 判断路径是否存在,不存在则新建
            checkFTPPath(ftpClient, uploadPath);
            // 保存文件到路径
            ftpClient.storeFile(fileName, input);
            log.info("您的文件【{}】上传成功。", fileName);
        } catch (IOException e) {
            log.error("FTP上传文件时出错", e);
            throw new BusinessException("sys.file.fail");
        } finally {
            // 关闭连接
            IOUtils.closeQuietly(input);
            closeFTP(ftpClient);
        }
    }

    /**
     * 上传文件
     *
     * @param input      输入流
     * @param uploadPath 保存路径
     * @param fileName   文件名(包含格式后缀)
     * @param ip
     * @param port
     * @param uname
     * @param pwd
     * @throws IOException
     */
    public static void upload(InputStream input, String uploadPath, String fileName, String ip, int port, String uname, String pwd) {
        FTPClient ftpClient = new FTPClient();
        try {
            // 获取FTP客户端
            ftpClient = connectFTP(ip, port, uname, pwd);
            // 判断路径是否存在,不存在则新建
            checkFTPPath(ftpClient, uploadPath);
            // 保存文件到路径
            ftpClient.storeFile(fileName, input);
            log.info("您的文件【{}】上传成功。", fileName);
        } catch (IOException e) {
            log.error("FTP上传文件时出错", e);
            throw new BusinessException("sys.file.fail");
        } finally {
            // 关闭连接
            IOUtils.closeQuietly(input);
            closeFTP(ftpClient);
        }
    }

    /**
     * 删除文件
     *
     * @param path      文件地址
     * @param ftpClient FTP客户端
     * @return
     * @throws IOException
     */
    public static Boolean deleteFile(String path, FTPClient ftpClient) {
        Boolean flag = false;
        try {
            //删除
            if (ftpClient != null) {
                flag = ftpClient.deleteFile(path);
                log.info("您的文件【{}】删除成功。", path);
            }
        } catch (IOException e) {
            log.error("FTP删除文件时出错", e);
            throw new BusinessException("sys.file.delete.fail");
        } finally {
            closeFTP(ftpClient);
        }
        return flag;
    }

    /**
     * 删除文件
     *
     * @param path  文件地址
     * @param ip
     * @param port
     * @param uname
     * @param pwd
     * @return
     * @throws IOException
     */
    public static Boolean deleteFile(String path, String ip, int port, String uname, String pwd) {
        Boolean flag = false;
        FTPClient ftpClient = new FTPClient();
        try {
            // 获取FTP客户端
            ftpClient = connectFTP(ip, port, uname, pwd);
            //删除
            if (ftpClient != null) {
                flag = ftpClient.deleteFile(path);
                log.info("您的文件【{}】删除成功。", path);
            }
        } catch (IOException e) {
            log.error("FTP删除文件时出错", e);
            throw new BusinessException("sys.file.delete.fail");
        } finally {
            closeFTP(ftpClient);
        }
        return flag;
    }

    /**
     * 删除目录
     *
     * @param path      目录地址
     * @param ftpClient FTP客户端
     * @return
     * @throws IOException
     */
    public static Boolean deleteDirectory(String path, FTPClient ftpClient) {
        Boolean flag = false;
        try {
            //删除
            if (ftpClient != null) {
                flag = ftpClient.removeDirectory(path);
                log.info("您的目录【{}】删除成功。", path);
            }
        } catch (IOException e) {
            log.error("FTP删除目录时出错", e);
            throw new BusinessException("sys.file.delete.fail");
        } finally {
            closeFTP(ftpClient);
        }
        return flag;
    }

    /**
     * 删除目录
     *
     * @param path  目录地址
     * @param ip
     * @param port
     * @param uname
     * @param pwd
     * @return
     * @throws IOException
     */
    public static Boolean deleteDirectory(String path, String ip, int port, String uname, String pwd) {
        Boolean flag = false;
        FTPClient ftpClient = new FTPClient();
        try {
            // 获取FTP客户端
            ftpClient = connectFTP(ip, port, uname, pwd);
            //删除
            if (ftpClient != null) {
                flag = ftpClient.removeDirectory(path);
                log.info("您的目录【{}】删除成功。", path);
            }
        } catch (IOException e) {
            log.error("FTP删除目录时出错", e);
            throw new BusinessException("sys.file.delete.fail");
        } finally {
            closeFTP(ftpClient);
        }
        return flag;
    }

    /**
     * 从ftp上下载
     *
     * @param output     输出流
     * @param remoteFile 文件路径
     * @param ftpClient  FTP客户端
     */
    public static void download(OutputStream output, String remoteFile, FTPClient ftpClient) {
        try {
            ftpClient.enterLocalPassiveMode();
            ftpClient.retrieveFile(remoteFile, output);
            output.flush();
            log.info("您的文件【{}】下载成功。", remoteFile);
        } catch (Exception e) {
            log.error("下载文件出错:", e);
        } finally {
            IOUtils.closeQuietly(output);
            closeFTP(ftpClient);
        }
    }

    /**
     * 从ftp上下载
     *
     * @param output     输出流
     * @param remoteFile 文件路径
     * @param ip
     * @param port
     * @param uname
     * @param pwd
     */
    public static void download(OutputStream output, String remoteFile, String ip, int port, String uname, String pwd) {
        FTPClient ftpClient = new FTPClient();
        try {
            // 获取FTP客户端
            ftpClient = connectFTP(ip, port, uname, pwd);

            ftpClient.enterLocalPassiveMode();
            ftpClient.retrieveFile(remoteFile, output);
            output.flush();
            log.info("您的文件【{}】下载成功。", remoteFile);
        } catch (Exception e) {
            log.error("下载文件出错:", e);
        } finally {
            IOUtils.closeQuietly(output);
            closeFTP(ftpClient);
        }
    }

    /**
     * 连接FTP服务器
     *
     * @param ip
     * @param port
     * @param uname
     * @param pwd
     * @return
     * @throws IOException
     */
    public static FTPClient connectFTP(String ip, int port, String uname, String pwd) throws IOException {
        FTPClient ftpClient = new FTPClient();
        // 优先设置编码格式,避免中文乱码
        ftpClient.setAutodetectUTF8(true);
        ftpClient.setCharset(CharsetUtil.UTF_8);
        ftpClient.setControlEncoding(CharsetUtil.UTF_8.name());

        ftpClient.connect(ip, port);
        boolean login = ftpClient.login(uname, pwd);
        if (!login) {
            throw new BusinessException("ftp连接失败,请检查配置");
        }

        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.setBufferSize(DEFAULT_BUFFER_SIZE);
        return ftpClient;
    }

    /**
     * 关闭连接
     *
     * @param ftpClient
     */
    public static void closeFTP(FTPClient ftpClient) {
        if (ftpClient != null) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                log.error("关闭FTP连接出错", e);
                throw new BusinessException("sys.file.fail");
            }
        }
    }

    /**
     * 校验路径是否存在,不存在则新建
     *
     * @param ftpClient
     * @param uploadPath
     * @throws IOException
     */
    private static void checkFTPPath(FTPClient ftpClient, String uploadPath) throws IOException {
        //判断路径是否存在,不存在则新建
        if (uploadPath != null) {
            String[] paths = uploadPath.split("/");
            StringBuffer tempPath = new StringBuffer();
            for (String path : paths) {
                if ((path != null) && (!"".equals(path.trim()))) {
                    String temp = tempPath.append("/").append(path.trim()).toString();
                    if ((!ftpClient.changeWorkingDirectory(temp)) && (ftpClient.makeDirectory(temp))) {
                        ftpClient.changeWorkingDirectory(temp);
                    }
                }
            }
        }
    }

}

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值