java实现FTP文件上传

陈不沉0516 2014-10-10 02:52:21
linux系统向windows系统上传文件,
服务器端为windows系统搭建FTP,
目前是上传图片为空图片,windows系统下测试可以上传成功,换成linux系统上传就是空图片,程序会一直执行,程序跑不动!代码下面贴出来!
求大神解答为什么这样!求大神给出liunx平台下的代码!
...全文
3540 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
baidu_33496053 2015-12-25
  • 打赏
  • 举报
回复
root和remoteUpLoadPath这个分别代表什么意思?InputStream 这个要怎么创建的?
紅塵 2014-10-11
  • 打赏
  • 举报
回复
引用 3 楼 u014737144 的回复:
[quote=引用 2 楼 lxp756010343 的回复:] 给个现成的代码吧,测试过的
public class FtpUtil {
    private static String OS = System.getProperty("os.name").toLowerCase();
    private FTPClient ftpClient;
    private String hostname;
    private int port;
    private String username;
    private String password;
    private String root;

    public FtpUtil(String hostname, int port, String username, String password, String root) {
        this.hostname = hostname;
        this.port = port;
        this.username = username;
        this.password = password;
        this.root = root;
        ftpClient = getClient();
    }

    public boolean ftpLogin() {
        boolean isLogin = false;
        this.ftpClient.setControlEncoding("GBK");
        try {
            if (this.port > 0) {
                this.ftpClient.connect(this.hostname, this.port);
            } else {
                this.ftpClient.connect(this.hostname);
            }
            // FTP服务器连接回答
            int reply = this.ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                this.ftpClient.disconnect();
                return isLogin;
            }
            this.ftpClient.login(this.username, this.password);
            // 设置传输协议
            this.ftpClient.enterLocalPassiveMode();
            this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            isLogin = true;
        } catch (Exception e) {
        	isLogin = false;
        	return isLogin;
            //throw new ServiceException(e.getMessage(), e);
        }
        this.ftpClient.setBufferSize(1024 * 2);
        //this.ftpClient.setDataTimeout(30 * 1000);
        return isLogin;
    }

    /**
     * @退出关闭服务器链接
     * */
    public void ftpLogOut() {
        if (null != this.ftpClient && this.ftpClient.isConnected()) {
            try {
                boolean reuslt = this.ftpClient.logout();// 退出FTP服务器
                if (reuslt) {
                }
            } catch (IOException e) {
                throw new ServiceException(e.getMessage(), e);
            } finally {
                try {
                    this.ftpClient.disconnect();// 关闭FTP服务器的连接
                } catch (IOException e) {
                    throw new ServiceException(e.getMessage(), e);
                }
            }
        }
    }

    public boolean uploadFile(InputStream inputStream, String remoteUpLoadPath, String fileName) {
        BufferedInputStream inStream = null;
        boolean success = false;
        try {
            ftpClient.changeWorkingDirectory(root);
            //ftpClient.makeDirectory(remoteUpLoadPath);
            createDirs(remoteUpLoadPath);
            //this.ftpClient.changeWorkingDirectory(remoteUpLoadPath);// 改变工作路径
            inStream = new BufferedInputStream(inputStream);
            success = this.ftpClient.storeFile(fileName, inStream);
            if (success == true) {
                return success;
            }
        } catch (FileNotFoundException e) {
            throw new ServiceException(e.getMessage(), e);
        } catch (IOException e) {
            throw new ServiceException(e.getMessage(), e);
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    throw new ServiceException(e.getMessage(), e);
                }
            }
        }
        return success;
    }

    public ByteArrayOutputStream downloadFile(String remoteDownLoadPath, String remoteFileName) {
        ByteArrayOutputStream outStream = null;
        boolean success = false;
        try {
            //this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);
            outStream = new ByteArrayOutputStream();
            if("/".equals(root)){
                success = this.ftpClient.retrieveFile(remoteDownLoadPath + remoteFileName, outStream);
            }else{
                success = this.ftpClient.retrieveFile(root + remoteDownLoadPath + remoteFileName, outStream);
            }
            if (success == true) {
                return outStream;
            }
        } catch (Exception e) {
            throw new ServiceException(e.getMessage(), e);
        } finally {
            if (null != outStream) {
                try {
                    outStream.flush();
                    outStream.close();
                } catch (IOException e) {
                    throw new ServiceException(e.getMessage(), e);
                }
            }
        }
        if (success == false) {
        }
        return null;
    }

    private FTPClient getClient(){
        FTPClient ftpClient = new FTPClient();
        ftpClient.setDefaultPort(port);
        ftpClient.configure(getClientConfig());
        ftpClient.setControlEncoding("GBK");
        return ftpClient;
    }

    private static FTPClientConfig getClientConfig(){
        String sysType = null;
        if(isLinux()){
            sysType = FTPClientConfig.SYST_UNIX;
        }else if(isWindows()){
            sysType = FTPClientConfig.SYST_NT;
        }
        FTPClientConfig config = new FTPClientConfig(sysType);
        config.setRecentDateFormatStr("yyyy-MM-dd HH:mm");
        return config;
    }

    public void createDirs(String remoteUpLoadPath) throws IOException {
        String[]dirs = remoteUpLoadPath.split("/");
        for(String dir : dirs){
            this.ftpClient.mkd(dir);
            this.ftpClient.changeWorkingDirectory(dir);

        }
    }

    private static boolean isLinux(){
        return OS.indexOf("linux") >= 0;
    }

    private static boolean isWindows(){
        return OS.indexOf("windows") >= 0;
    }
}
root参数是做什么的,可以给个@Test测试程序吗? 谢谢[/quote] FtpUtil ftpUtil = new FtpUtil(localFtpHost, localPort, localFtpUserName, localFtpPassword, localFtpRoot); ftpUtil.ftpLogin(); ftpUtil.uploadFile(inputStream, dst_local.substring(0, dst_local.lastIndexOf("/") + 1),dst_local.substring(dst_local.lastIndexOf("/") + 1)); ftpUtil.ftpLogOut(); root 上传到服务器的根路径 如“/” dst_local:上传到服务器的完整路径 如:/aaa/bbb/cccc/dddd/qqqq/sssss/gggggg/aa.jpg
陈不沉0516 2014-10-11
  • 打赏
  • 举报
回复
引用 2 楼 lxp756010343 的回复:
给个现成的代码吧,测试过的
public class FtpUtil {
    private static String OS = System.getProperty("os.name").toLowerCase();
    private FTPClient ftpClient;
    private String hostname;
    private int port;
    private String username;
    private String password;
    private String root;

    public FtpUtil(String hostname, int port, String username, String password, String root) {
        this.hostname = hostname;
        this.port = port;
        this.username = username;
        this.password = password;
        this.root = root;
        ftpClient = getClient();
    }

    public boolean ftpLogin() {
        boolean isLogin = false;
        this.ftpClient.setControlEncoding("GBK");
        try {
            if (this.port > 0) {
                this.ftpClient.connect(this.hostname, this.port);
            } else {
                this.ftpClient.connect(this.hostname);
            }
            // FTP服务器连接回答
            int reply = this.ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                this.ftpClient.disconnect();
                return isLogin;
            }
            this.ftpClient.login(this.username, this.password);
            // 设置传输协议
            this.ftpClient.enterLocalPassiveMode();
            this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            isLogin = true;
        } catch (Exception e) {
        	isLogin = false;
        	return isLogin;
            //throw new ServiceException(e.getMessage(), e);
        }
        this.ftpClient.setBufferSize(1024 * 2);
        //this.ftpClient.setDataTimeout(30 * 1000);
        return isLogin;
    }

    /**
     * @退出关闭服务器链接
     * */
    public void ftpLogOut() {
        if (null != this.ftpClient && this.ftpClient.isConnected()) {
            try {
                boolean reuslt = this.ftpClient.logout();// 退出FTP服务器
                if (reuslt) {
                }
            } catch (IOException e) {
                throw new ServiceException(e.getMessage(), e);
            } finally {
                try {
                    this.ftpClient.disconnect();// 关闭FTP服务器的连接
                } catch (IOException e) {
                    throw new ServiceException(e.getMessage(), e);
                }
            }
        }
    }

    public boolean uploadFile(InputStream inputStream, String remoteUpLoadPath, String fileName) {
        BufferedInputStream inStream = null;
        boolean success = false;
        try {
            ftpClient.changeWorkingDirectory(root);
            //ftpClient.makeDirectory(remoteUpLoadPath);
            createDirs(remoteUpLoadPath);
            //this.ftpClient.changeWorkingDirectory(remoteUpLoadPath);// 改变工作路径
            inStream = new BufferedInputStream(inputStream);
            success = this.ftpClient.storeFile(fileName, inStream);
            if (success == true) {
                return success;
            }
        } catch (FileNotFoundException e) {
            throw new ServiceException(e.getMessage(), e);
        } catch (IOException e) {
            throw new ServiceException(e.getMessage(), e);
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    throw new ServiceException(e.getMessage(), e);
                }
            }
        }
        return success;
    }

    public ByteArrayOutputStream downloadFile(String remoteDownLoadPath, String remoteFileName) {
        ByteArrayOutputStream outStream = null;
        boolean success = false;
        try {
            //this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);
            outStream = new ByteArrayOutputStream();
            if("/".equals(root)){
                success = this.ftpClient.retrieveFile(remoteDownLoadPath + remoteFileName, outStream);
            }else{
                success = this.ftpClient.retrieveFile(root + remoteDownLoadPath + remoteFileName, outStream);
            }
            if (success == true) {
                return outStream;
            }
        } catch (Exception e) {
            throw new ServiceException(e.getMessage(), e);
        } finally {
            if (null != outStream) {
                try {
                    outStream.flush();
                    outStream.close();
                } catch (IOException e) {
                    throw new ServiceException(e.getMessage(), e);
                }
            }
        }
        if (success == false) {
        }
        return null;
    }

    private FTPClient getClient(){
        FTPClient ftpClient = new FTPClient();
        ftpClient.setDefaultPort(port);
        ftpClient.configure(getClientConfig());
        ftpClient.setControlEncoding("GBK");
        return ftpClient;
    }

    private static FTPClientConfig getClientConfig(){
        String sysType = null;
        if(isLinux()){
            sysType = FTPClientConfig.SYST_UNIX;
        }else if(isWindows()){
            sysType = FTPClientConfig.SYST_NT;
        }
        FTPClientConfig config = new FTPClientConfig(sysType);
        config.setRecentDateFormatStr("yyyy-MM-dd HH:mm");
        return config;
    }

    public void createDirs(String remoteUpLoadPath) throws IOException {
        String[]dirs = remoteUpLoadPath.split("/");
        for(String dir : dirs){
            this.ftpClient.mkd(dir);
            this.ftpClient.changeWorkingDirectory(dir);

        }
    }

    private static boolean isLinux(){
        return OS.indexOf("linux") >= 0;
    }

    private static boolean isWindows(){
        return OS.indexOf("windows") >= 0;
    }
}
root参数是做什么的,可以给个@Test测试程序吗? 谢谢
紅塵 2014-10-10
  • 打赏
  • 举报
回复
给个现成的代码吧,测试过的
public class FtpUtil {
    private static String OS = System.getProperty("os.name").toLowerCase();
    private FTPClient ftpClient;
    private String hostname;
    private int port;
    private String username;
    private String password;
    private String root;

    public FtpUtil(String hostname, int port, String username, String password, String root) {
        this.hostname = hostname;
        this.port = port;
        this.username = username;
        this.password = password;
        this.root = root;
        ftpClient = getClient();
    }

    public boolean ftpLogin() {
        boolean isLogin = false;
        this.ftpClient.setControlEncoding("GBK");
        try {
            if (this.port > 0) {
                this.ftpClient.connect(this.hostname, this.port);
            } else {
                this.ftpClient.connect(this.hostname);
            }
            // FTP服务器连接回答
            int reply = this.ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                this.ftpClient.disconnect();
                return isLogin;
            }
            this.ftpClient.login(this.username, this.password);
            // 设置传输协议
            this.ftpClient.enterLocalPassiveMode();
            this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            isLogin = true;
        } catch (Exception e) {
        	isLogin = false;
        	return isLogin;
            //throw new ServiceException(e.getMessage(), e);
        }
        this.ftpClient.setBufferSize(1024 * 2);
        //this.ftpClient.setDataTimeout(30 * 1000);
        return isLogin;
    }

    /**
     * @退出关闭服务器链接
     * */
    public void ftpLogOut() {
        if (null != this.ftpClient && this.ftpClient.isConnected()) {
            try {
                boolean reuslt = this.ftpClient.logout();// 退出FTP服务器
                if (reuslt) {
                }
            } catch (IOException e) {
                throw new ServiceException(e.getMessage(), e);
            } finally {
                try {
                    this.ftpClient.disconnect();// 关闭FTP服务器的连接
                } catch (IOException e) {
                    throw new ServiceException(e.getMessage(), e);
                }
            }
        }
    }

    public boolean uploadFile(InputStream inputStream, String remoteUpLoadPath, String fileName) {
        BufferedInputStream inStream = null;
        boolean success = false;
        try {
            ftpClient.changeWorkingDirectory(root);
            //ftpClient.makeDirectory(remoteUpLoadPath);
            createDirs(remoteUpLoadPath);
            //this.ftpClient.changeWorkingDirectory(remoteUpLoadPath);// 改变工作路径
            inStream = new BufferedInputStream(inputStream);
            success = this.ftpClient.storeFile(fileName, inStream);
            if (success == true) {
                return success;
            }
        } catch (FileNotFoundException e) {
            throw new ServiceException(e.getMessage(), e);
        } catch (IOException e) {
            throw new ServiceException(e.getMessage(), e);
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    throw new ServiceException(e.getMessage(), e);
                }
            }
        }
        return success;
    }

    public ByteArrayOutputStream downloadFile(String remoteDownLoadPath, String remoteFileName) {
        ByteArrayOutputStream outStream = null;
        boolean success = false;
        try {
            //this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);
            outStream = new ByteArrayOutputStream();
            if("/".equals(root)){
                success = this.ftpClient.retrieveFile(remoteDownLoadPath + remoteFileName, outStream);
            }else{
                success = this.ftpClient.retrieveFile(root + remoteDownLoadPath + remoteFileName, outStream);
            }
            if (success == true) {
                return outStream;
            }
        } catch (Exception e) {
            throw new ServiceException(e.getMessage(), e);
        } finally {
            if (null != outStream) {
                try {
                    outStream.flush();
                    outStream.close();
                } catch (IOException e) {
                    throw new ServiceException(e.getMessage(), e);
                }
            }
        }
        if (success == false) {
        }
        return null;
    }

    private FTPClient getClient(){
        FTPClient ftpClient = new FTPClient();
        ftpClient.setDefaultPort(port);
        ftpClient.configure(getClientConfig());
        ftpClient.setControlEncoding("GBK");
        return ftpClient;
    }

    private static FTPClientConfig getClientConfig(){
        String sysType = null;
        if(isLinux()){
            sysType = FTPClientConfig.SYST_UNIX;
        }else if(isWindows()){
            sysType = FTPClientConfig.SYST_NT;
        }
        FTPClientConfig config = new FTPClientConfig(sysType);
        config.setRecentDateFormatStr("yyyy-MM-dd HH:mm");
        return config;
    }

    public void createDirs(String remoteUpLoadPath) throws IOException {
        String[]dirs = remoteUpLoadPath.split("/");
        for(String dir : dirs){
            this.ftpClient.mkd(dir);
            this.ftpClient.changeWorkingDirectory(dir);

        }
    }

    private static boolean isLinux(){
        return OS.indexOf("linux") >= 0;
    }

    private static boolean isWindows(){
        return OS.indexOf("windows") >= 0;
    }
}
陈不沉0516 2014-10-10
  • 打赏
  • 举报
回复
package Utils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; import org.junit.Test; public class FTPUtil { /** * Description: 向FTP服务器上传文件 * * @Version 1.0 * @param url * FTP服务器hostname * @param port * FTP服务器端口 * @param username * FTP登录账号 * @param password * FTP登录密码 * @param path * FTP服务器保存目录 * @param filename * 上传到FTP服务器上的文件名 * @param input * 输入流 * @return 成功返回true,否则返回false * */ public static boolean uploadFile(String url,// FTP服务器hostname int port,// FTP服务器端口 String username, // FTP登录账号 String password, // FTP登录密码 String path, // FTP服务器保存目录 String filename, // 上传到FTP服务器上的文件名 InputStream input // 输入流 ) { boolean success = false; FTPClient ftp = new FTPClient(); ftp.setControlEncoding("GBK"); try { int reply; ftp.connect(url, port);// 连接FTP服务器 // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器 ftp.login(username, password);// 登录 reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } ftp.setFileType(FTPClient.BINARY_FILE_TYPE); ftp.makeDirectory(path); ftp.changeWorkingDirectory(path); ftp.storeFile(filename, input); input.close(); ftp.logout(); success = true; } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return success; } /** * @deprecated将本地文件上传到FTP服务器上 * * @param url * 服务器hostname * @param port * 服务器端口 * @param username * FTP登陆名 * @param password * FT登陆密码 * @param path * FTP 服务器保存目录 * @param filename * 服务器保存文件名 * @param orginfilename * 上传文件路径 */ public static void upLoadFromProduction(String url,// FTP服务器hostname int port,// FTP服务器端口 String username, // FTP登录账号 String password, // FTP登录密码 String path, // FTP服务器保存目录 String filename, // 上传到FTP服务器上的文件名 String orginfilename // 输入流文件名 ) { try { FileInputStream in = new FileInputStream(new File(orginfilename)); boolean flag = uploadFile(url, port, username, password, path, filename, in); System.out.println(flag); } catch (Exception e) { e.printStackTrace(); } } @Test public void testFTP() { upLoadFromProduction("192.168.1.119“, 8088, "user", "123456", "/" ,"1Test1010.jpg", "E://aa//a.jpg"); //这个是在windows系统下的,可以成功 upLoadFromProduction("192.168.1.119“, 8088, "user", "123456", "/" ,"1Test1010.jpg", "//home//user//test.jpg"); //这个市是linux的,传过来是空图片,并且程序一直运行,跑步动! } }

62,634

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧