FTPClient 应用示例

转:http://hi.baidu.com/suixinyu_545/item/615b8c2afa63b49db632633f

 

 

java ftpclient生成目录,上传图片

 

package com.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.util.PropertiesUtil;

public class ImageUploadFtpUtil {
    private static Logger log = Logger.getLogger(ImageUploadFtpUtil.class);
    
    static String ftpUsername;
    static String ftpPassword;
    static int ftpPort;
    static String ftpHost;
    static String ftpLimitIps;
    
    static{
        ftpUsername = PropertiesUtil.getValue("const.properties", "ciftpUserName");
        ftpPassword = PropertiesUtil.getValue("const.properties", "ciftpPassword");
        ftpPort = Integer.valueOf(PropertiesUtil.getValue("const.properties", "ciftpPort"));
        ftpHost = PropertiesUtil.getValue("const.properties", "ciftpHost");
        ftpLimitIps = PropertiesUtil.getValue("const.properties", "ciftpLimitIps");
    }
    
    public static boolean upload(CommonsMultipartFile cmf,String fileName,String ftpDir)
    {
        if(fileName.indexOf(".")<0)
        {
            String ex = ImageUploadFtpUtil.getEx(cmf);
            fileName += (ex);
        }
        boolean result = false;
        if (cmf != null && !cmf.isEmpty()) {// 如果有文章中带有附件
            InputStream is = null;// 附件输入流
            try {
                is = cmf.getInputStream();
                result = uploadFile(ftpHost, ftpPort,ftpUsername,ftpPassword , ftpDir, fileName, is);
            } catch (Exception exception) {
                log.error("上传文件流出错",exception);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        log.error("关闭上传文件流出错",e);
                        e.printStackTrace();
                    }
                }
            }
        }
        return result;
    }
    
    public static String getEx(CommonsMultipartFile cmf)
    {
        if(cmf == null)
            return "";
        //生成后缀
        String ex = cmf.getOriginalFilename();
        String[] arr = ex.split("\\.");
        if(arr.length>1)
        {
            ex = arr[arr.length-1];
            return "."+ex;
        }
        ex = cmf.getContentType();
        ex = ex.split("/")[1];
        if("jpeg".equalsIgnoreCase(ex))
        {
            ex = "jpg";
        }
        else if("x-rar".equalsIgnoreCase(ex))
        {
            ex = "rar";
        }
        else if("x-gzip".equalsIgnoreCase(ex))
        {
            ex = "tar.gz";
        }
        return "."+ex;
    }
    
    /**
     * Description: 向FTP服务器上传文件
     * 
     * @Version1.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();
        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.setControlEncoding("utf-8");
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.enterLocalPassiveMode();
//            listRemoteAllFiles(ftp);
            success = createDir(ftp,path);
            if(!success)
            {
                log.error("ftp 生成目录或转换目录失败");
            }else
            {
                success = ftp.storeFile(new String(filename.getBytes("UTF-8"),"iso-8859-1"), input);
            }    
            input.close();
            ftp.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
                ftp=null;
            }
        }
        return success;
    }
    /**
     * 根据路径创建目录,并会把工作目录自动转换到最后子目录
     * @param ftpClient
     * @param path
     * @return
     * @throws IOException
     *
     * @author kinglo
     * Mar 19, 2012
     */
    private static boolean createDir(FTPClient ftpClient,String path) throws IOException
    {
        System.out.println("crateDir: "+path);
        if(path == null|| path == "" || ftpClient == null)
        {
            return false;
        }
        String[] paths = path.split("/");
        for (int i = 0; i < paths.length; i++)
        {
            FTPFile[] ffs = ftpClient.listDirectories(paths[i]);
            boolean is = false;
            boolean f = true;
            if(f)
            {
                for (FTPFile ftpFile : ffs)
                {
                    if(ftpFile.getName() == paths[i])
                    {
                        ftpClient.changeWorkingDirectory(paths[i]);
                        is = true;
                        break;
                    }
                }
            }
            if(!is)
            {
                f = false;
                boolean a,x=false;
                a = ftpClient.makeDirectory(new String(paths[i].getBytes("UTF-8"),"iso-8859-1"));
                x = ftpClient.changeWorkingDirectory(paths[i]);
                if(!a || !x) return false;
            }
        }
        return true;
    }
   
    /**
     * 将本地文件上传到FTP服务器上
     * 
     */
    static public void testUpLoadFromDisk() {
        try {
            FileInputStream in = new FileInputStream(new File("/home/pm/hzk.jpg"));
            boolean flag = uploadFile("127.0.0.1", 21, "ftptest",
                    "test", "2012/9/8", "test.jpg", in);
            System.out.println(flag);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 在FTP服务器上生成一个文件,并将一个字符串写入到该文件中
     * 
     */
    static public void testUpLoadFromString() {
        try {
            String str = "Hello!这是要写入的字符串!";
            InputStream input = new ByteArrayInputStream(str.getBytes("utf-8"));
            boolean flag = uploadFile("127.0.0.1", 21, "ftptest",
                    "test", "ftptest", "test.txt", input);
            System.out.println(flag);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 列出Ftp服务器上的所有文件和目录
     * 
     */
    public static void listRemoteAllFiles(FTPClient ftp) {
        try {
            String[] names = ftp.listNames();
            for (int i = 0; i < names.length; i++) {
                System.out.println(names[i]);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //这个就是本地复制粘贴图片,跟上面代码没有半毛钱关系,请无视..
    public static boolean copyImage(String fromPath, String toPath, String bookId){
        boolean isResult = false;
//         String path = "/home/pm/test.jpg"; 
        System.out.println("fromPath:"+fromPath);
            File file = new File(fromPath);  
            FileInputStream fis;  
            try  
            {  
                fis = new FileInputStream(file);  
                byte[] b;  
                b = new byte[fis.available()];  
                StringBuilder str = new StringBuilder();// 不建议用String  
                fis.read(b);  
                for (byte bs : b)  
                {  
                    str.append(Integer.toBinaryString(bs));// 转换为二进制  
                }  
               
                String savePath = toPath + "/" + bookId + ".jpg";
                System.out.println("savePath:"+savePath);
                File apple = new File(savePath);// 把字节数组的图片写到另一个地方  "/home/pm/test1.jpg"
                FileOutputStream fos = new FileOutputStream(apple);  
                fos.write(b);  
                fos.flush();  
                fos.close();  
            }  
            catch (FileNotFoundException e)  
            {  
                e.printStackTrace();  
            }  
            catch (IOException e)  
            {  
                e.printStackTrace();  
            }  
        return isResult;
    }
//    public static void main(String[] args)  
//    {  
        copyImage("/home/pm/test.jpg","/home/pm","2012");        
//    }  
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值