关于ftp文件服务器上传下载遇到的一些坑

来源:互联网 发布:福利彩票预测软件 编辑:程序博客网 时间:2024/05/19 23:13
  1. 项目需要做文件的上传下载,由后台定时生成word,pdf文件上传到ftp服务器,然后供客户端下载。聊聊其中遇到的坑
    在文件上传的时候,遇到坑之一,编码问题,上传需要对文件进行转码,所以在上传的时候必须进行转码,不然会报错,
    遇到的第二个问题:在上传文件的时候,如果服务器需要创建目录;当时创建多层文件夹的方式在windows下创建成功,丢在服务器上后就报错。
    第三个问题:在为客户端提供下载的时候,一直显示报错,原因在客户端开启了防火墙。ftp连接时需要开启被动模式 下面贴代码:

    引用块内容package com.bicap.cloud.ftp.config;

    import org.apache.commons.net.ftp.; import java.io.; import
    java.text.SimpleDateFormat; import java.util.StringTokenizer;

    /* Created by songlinhai on 2017/8/15 0015. */ public class
    FTPUtils {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");private static String encoding = System.getProperty("file.encoding");/** * Description: 向FTP服务器上传文件 * * @param host     FTP服务器hostname * @param port     FTP服务器端口 * @param username FTP登录账号 * @param password FTP登录密码 * @param basePath FTP服务器基础目录 * @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath * @param filename 上传到FTP服务器上的文件名 * @param input    输入流 * @return 成功返回true,否则返回false */public static boolean uploadFile(String host, int port, String username, String password, String basePath,                                 String filePath, String filename, InputStream input) {    boolean result = false;    FTPClient ftp = new FTPClient();    try {        int reply;        ftp.connect(host, port);// 连接FTP服务器 //            ftp.enterLocalActiveMode();    //主动模式        ftp.enterLocalPassiveMode(); //被动模式        // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器        ftp.login(username, password);// 登录        // 检验是否连接成功        reply = ftp.getReplyCode(); //            System.out.println("===========" + reply);        if (!FTPReply.isPositiveCompletion(reply)) {            System.out.println("连接失败");            ftp.disconnect();            return result;        }

    //切换到上传目录,这种创建多层文件夹方式在linux会报错 //if
    (!ftp.changeWorkingDirectory(basePath + filePath)) {
    //如果目录不存在创建目录
    // String[] dirs = filePath.split(“/”);
    // String tempPath = basePath;
    // for (String dir : dirs) {
    // if (null == dir || “”.equals(dir)) continue;
    // tempPath += “/” + dir;
    // if (!ftp.changeWorkingDirectory(tempPath)) {
    // if (!ftp.makeDirectory(tempPath)) {
    // return result;
    // } else {
    // ftp.changeWorkingDirectory(tempPath);
    // }
    // }
    // }
    // }

            System.out.println("=====" + basePath);        //切换到上传目录,这种方式在windows和linux都实用        boolean flag = false;        if (ftp.changeWorkingDirectory(basePath)) {            try {                    filePath = filePath.replace("/", "");                    if (!ftp.changeWorkingDirectory(filePath)){                        flag = ftp.makeDirectory(filePath);                        if(flag){                            ftp.changeWorkingDirectory(filePath);                        }                    }            } catch (Exception e) {                e.printStackTrace();            }        } else {            try {                flag = ftp.makeDirectory(basePath);                if (flag) {                    if (ftp.changeWorkingDirectory(basePath)) {                        flag = ftp.makeDirectory(filePath.replace("/", ""));                        if(flag){                            ftp.changeWorkingDirectory(filePath.replace("/",""));                        }                    }                } else {                    System.out.println("创建失败");                }            } catch (Exception e) {            }        }        //设置上传文件的类型为二进制类型        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);        //windows下ftp服务器默认编码为GBK        ftp.setControlEncoding("GBK");        //上传文件,注意这里需要对文件名进行转码        if (!ftp.storeFile(new String(filename.getBytes("UTF-8"), "iso-8859-1"), input)) {            return result;        }        input.close();        ftp.logout();        result = true;        System.out.println("上传成功");    } catch (IOException e) {        e.printStackTrace();    } finally {        if (ftp.isConnected()) {            try {                ftp.disconnect();            } catch (IOException ioe) {            }        }    }    return result;}/** * Description: 从FTP服务器下载文件 * * @param host       FTP服务器hostname * @param port       FTP服务器端口 * @param username   FTP登录账号 * @param password   FTP登录密码 * @param remotePath FTP服务器上的相对路径 * @param fileName   要下载的文件名 * @param localPath  下载后保存到本地的路径 * @return */      public static boolean downloadFile(String host, int port, String username, String password, String remotePath,                                   String fileName, String localPath) {    boolean result = false;    FTPClient ftp = new FTPClient();    try {        int reply;        ftp.connect(host, port);        // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器 //            ftp.enterLocalActiveMode();    //主动模式        ftp.enterLocalPassiveMode();        ftp.login(username, password);// 登录        reply = ftp.getReplyCode();        if (!FTPReply.isPositiveCompletion(reply)) {            ftp.disconnect();            return result;        }        ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录        FTPFile[] fs = ftp.listFiles();        String fileNames = null;        for (FTPFile ff : fs) {            fileNames = new String(ff.getName().getBytes("iso-8859-1"), "UTF-8");            System.out.println("====" + fileNames);            if (fileNames.equals(fileName)) {                File localFile = new File(localPath + "/" + fileNames);                OutputStream is = new FileOutputStream(localFile);                ftp.setFileType(FTPClient.BINARY_FILE_TYPE);                ftp.retrieveFile(ff.getName(), is);                is.close();            }        }        ftp.logout();        result = true;    } catch (IOException e) {        e.printStackTrace();    } finally {        if (ftp.isConnected()) {            try {                ftp.disconnect();            } catch (IOException ioe) {            }        }    }    return result;}/**//** * 将本地文件上传到FTP服务器上demo *//*public void testUpLoadFile() {    Long time = System.currentTimeMillis();    String data = sdf.format(time);    try {        FileInputStream in = new FileInputStream(new File("F:/成功.doc"));        boolean flag = uploadFile("10.10.1.102", 21, "ftp", "ftp", "/2016-08-16", "/3", "成功.doc", in);        System.out.println(flag);    } catch (FileNotFoundException e) {        e.printStackTrace();    }}*//** * 将FTP服务器上文件下载到本地demo */public void testDownFile() {    try {        boolean flag = downloadFile("10.10.1.102", 21, "ftp",                "ftp", "/2017-09-22/1", "成都电力局日报.doc", "F:/");        System.out.println(flag);    } catch (Exception e) {        e.printStackTrace();    }}

    // public static void main(String[] args) { // FTPUtils fa
    = new FTPUtils(); //// fa.testUpLoadFile(); // fa.testDownFile(); //// } // }

    }

原创粉丝点击