Java實現FTP上傳圖片到服務器

應公司開發需要,需要從網絡上抓取一些圖片
如何將圖片使用代碼的方式放到服務器的目錄下
公司對我開了一個端口爲911的FTP賬號
下面的代碼就是Java模擬FTP將本地保存的圖片上傳到服務器

package com.dd1258.ftp;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

public class FTP {
    private static Logger logger = Logger.getLogger(FTP.class);

    public static void main(String[] args) {
        String ftpHost = "************";
        int ftpPort = 911;
        String ftpUserName = "******************";
        String ftpPassword = "*******************";
        String fileContent = "";
        String writeTempFielPath = "";
        String ftpPath = "";
        FTP f = new FTP();
        f.upload(ftpPath, ftpUserName, ftpPassword, ftpHost, ftpPort, fileContent, writeTempFielPath);
    }


    /**
     * 本地上傳文件到FTP服務器
     *
     * @param ftpPath
     *            遠程文件路徑FTP
     * @throws IOException
     */
    public void upload(String ftpPath, String ftpUserName, String ftpPassword, String ftpHost, int ftpPort,
            String fileContent, String writeTempFielPath) {
        FTPClient ftpClient = null;
        System.out.println("開始上傳文件到FTP.");
        try {
            ftpClient = FTP.getFTPClient(ftpHost, ftpPassword, ftpUserName, ftpPort);
            // 設置PassiveMode傳輸
            ftpClient.enterLocalPassiveMode();
            // 設置以二進制流的方式傳輸
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            // 對遠程目錄的處理
            String remoteFileName = ftpPath; // -> /ddweb/LJ_TEST/f.txt
            if (ftpPath.contains("/")) {
                remoteFileName = ftpPath.substring(ftpPath.lastIndexOf("/") + 1);
            }
            // FTPFile[] files = ftpClient.listFiles(new
            // String(remoteFileName));
            // 先把文件寫在本地。在上傳到FTP上最後在刪除
            //boolean writeResult = write(remoteFileName, fileContent, writeTempFielPath);
            if (true) {
                //File f = new File(writeTempFielPath + "/" + remoteFileName);
                File f = new File("G:/PythonSource/DD_MV/img/3.jpg");
                InputStream in = new FileInputStream(f);
                String lastpath = "/ddweb/LJ_TEST/"+"a.jpg";
                ftpClient.storeFile(lastpath, in);
                in.close();
                logger.info("上傳文件" + remoteFileName + "到FTP成功!");
                //f.delete();
            } else {
                logger.info("寫文件失敗!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 將配置文件寫到本地去   返回true和false
     * @param fileName
     * @param fileContext
     * @param writeTempFielPath
     * @return
     */
    public boolean write(String fileName, String fileContext, String writeTempFielPath) {
        try {
            logger.info("開始寫配置文件");
            File f = new File(writeTempFielPath + "/" + fileName);
            if (!f.exists()) {
                if (!f.createNewFile()) {
                    logger.info("文件不存在,創建失敗!");
                }
            }
            BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
            bw.write(fileContext.replaceAll("\n", "\r\n"));
            bw.flush();
            bw.close();
            return true;
        } catch (Exception e) {
            logger.error("寫文件沒有成功");
            e.printStackTrace();
            return false;
        }
    }

    public static FTPClient getFTPClient(String ftpHost, String ftpPassword,  
            String ftpUserName, int ftpPort) {  
        FTPClient ftpClient = null;  
        try {  
            ftpClient = new FTPClient();  
            ftpClient.connect(ftpHost, ftpPort);// 連接FTP服務器  
            ftpClient.login(ftpUserName, ftpPassword);// 登陸FTP服務器  
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {  
                logger.info("未連接到FTP,用戶名或密碼錯誤。");  
                ftpClient.disconnect();  
            } else {  
                logger.info("FTP連接成功。");  
            }  
        } catch (SocketException e) {  
            e.printStackTrace();  
            logger.info("FTP的IP地址可能錯誤,請正確配置。");  
        } catch (IOException e) {  
            e.printStackTrace();  
            logger.info("FTP的端口錯誤,請正確配置。");  
        }  
        System.out.println("---------------------連接成功----------------------");
        System.out.println(ftpClient);
        return ftpClient;  
    }  
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章