上傳文件至ftp

1.本地文件上傳到eclipse

  1)處理圖片上傳的類

 package com.gy.apply.admin.platform.contract.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.gy.common.attach.GYFTPClientImpl;
import com.gy.common.attach.GYFtpClient;
import com.gy.common.controller.ExceptionController;
import com.gy.apply.admin.platform.contract.controller.ScaleImage;

/**
 * Simple to Introduction
 *
 * @category 圖片上傳
 * @projectName person-web
 * @package com.gy.person.controller.FileUploadController.java
 * @className FileUploadController
 * @description 實名認證圖片上傳
 * @author zhangnn
 * @createDate 2014-9-1 下午12:29:15
 * @updateUser zhangnn
 * @updateDate 2014-9-1 下午12:29:15
 * @updateRemark 說明本次修改內容
 * @version v0.0.1
 */
@Controller
@RequestMapping("/file")
public class FileUploadController extends ExceptionController {

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request,
            HttpServletResponse response, Exception ex) {
        return null;
    }

    /**
     * 這裏用的是MultipartFile[] myfiles參數,所以前臺就要用<input type="file"
     * name="myfiles"/>
     * 上傳文件完畢後返回給前臺[0`filepath],0表示上傳成功(後跟上傳後的文件路徑),1表示失敗(後跟失敗描述)
     */
    @RequestMapping(value = "/fileUpload")
    public String addUser(@RequestParam("customId") String customId,@RequestParam("picName") String picName,
            @RequestParam MultipartFile[] myfiles, HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        // 可以在上傳文件的同時接收其它參數
        logger.info("收到用戶的文件上傳請求");
        logger.info("#####################" + picName);
        InetAddress addr = InetAddress.getLocalHost();
        String ip = addr.getHostAddress().toString();//獲得本機IP
        
        // 如果用的是Tomcat服務器,則文件會上傳到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夾中
        // 這裏實現文件上傳操作用的是commons.io.FileUtils類,它會自動判斷/upload是否存在,不存在會自動創建
        String realPath = request.getSession().getServletContext()
                .getRealPath("/upload");
        // 設置響應給前臺內容的數據格式
        response.setContentType("text/plain; charset=UTF-8");
        // 設置響應給前臺內容的PrintWriter對象
        PrintWriter out = response.getWriter();
        // 上傳文件的原名(即上傳前的文件名字)
        String originalFilename = null;
        // 如果只是上傳一個文件,則只需要MultipartFile類型接收文件即可,而且無需顯式指定@RequestParam註解
        // 如果想上傳多個文件,那麼這裏就要用MultipartFile[]類型來接收文件,並且要指定@RequestParam註解
        // 上傳多個文件時,前臺表單中的所有<input
        // type="file"/>的name都應該是myfiles,否則參數裏的myfiles無法獲取
        for (MultipartFile myfile : myfiles) {
            if (myfile.isEmpty()) {
                out.print("1`請選擇文件後上傳");
                out.flush();
                return null;
            } else {
                String myfileName = myfile.getOriginalFilename().trim();
                originalFilename = customId +System.currentTimeMillis()+picName
                        + myfileName.substring(myfileName.lastIndexOf("."));
                logger.info("文件原名: " + originalFilename);
                logger.info("文件名稱: " + myfile.getName());
                logger.info("文件長度: " + myfile.getSize());
                logger.info("文件類型: " + myfile.getContentType());
                if (myfile.getSize() > 1000000) {
                    out.print("3`文件過大");
                    out.flush();
                    return null;
                } else {
                    try {
                        // 這裏不必處理IO流關閉的問題,因爲FileUtils.copyInputStreamToFile()方法內部會自動把用到的IO流關掉
                        // 此處也可以使用Spring提供的MultipartFile.transferTo(File
                        // dest)方法實現文件
                        FileUtils.copyInputStreamToFile(
                                myfile.getInputStream(), new File(realPath,
                                        originalFilename.trim()));
                        //判斷上傳的文件是不是圖片,如果是,就生成縮略圖
                        
                        // 上傳文件後,生成縮略圖,放在small文件夾下;
                        ScaleImage si = new ScaleImage();
                        String small = realPath + "/small";
                        String oPath = realPath + "/" + originalFilename.trim();
                        String thumbPath = small + "/" + originalFilename.trim();
                        //創建small文件夾
                        File smallDir = new File(small);
                        if(!smallDir.exists()){
                            smallDir.mkdirs();
                        }
                        si.saveImageAsJpg(oPath,thumbPath, 140, 90);
                        GYFtpClient ftp = new GYFTPClientImpl();
                        try {
                            ftp.setHostName("192.168.1.173");
                            ftp.setUserName("admin");
                            ftp.setPassword("admin");
                            ftp.setPort(21);
                            ftp.connect();
                            File file = new File(realPath);   
                            ftp.upload("apply",file);
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        
                    } catch (Exception e) {
                        logger.info("文件[" + originalFilename+ "]上傳失敗,堆棧軌跡如下");
                        logger.error("異常", e);
                        out.print("1`文件上傳失敗,請重試!!");
                        out.flush();
                        return null;
                    }
                }
            }
        }
        out.print("0`" +"http://"+ip+":8080"+ request.getContextPath() + "/upload/"
                + originalFilename.trim());
        out.print("#" + originalFilename.trim());
        out.flush();
        return null;
    }

}

2)如果上傳的是圖片,生成縮略圖的類

package com.gy.apply.admin.platform.contract.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

/**
 *
 * Simple to Introduction
 * @category          Simple to Introduction
 * @projectName   person-web
 * @package           com.gy.person.util.ScaleImage.java
 * @className       ScaleImage
 * @description      生成縮略圖
 * @author              zhoudq
 * @createDate       2014-8-27 下午4:59:54  
 * @updateUser      zhoudq
 * @updateDate      2014-8-27 下午4:59:54
 * @updateRemark 說明本次修改內容
 * @version              v0.0.1
 */
public class ScaleImage {

    private int width;

    private int height;

    private int scaleWidth;

    double support = (double) 3.0;

    double PI = (double) 3.14159265358978;

    double[] contrib;

    double[] normContrib;

    double[] tmpContrib;

    int startContrib, stopContrib;

    int nDots;

    int nHalfDots;

    /**
     * Start: Use Lanczos filter to replace the original algorithm for image
     * scaling. Lanczos improves quality of the scaled image modify by :blade
     */

    public static void main(String[] args) {
//        ScaleImage is = new ScaleImage();
//        try {
//            is.saveImageAsJpg("E:/test/img/1409109501890catanddog.jpg", "E:/test/img/small/1409109501890catanddog.jpg", 120,
//                    120);
//            System.out.println("success");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }
 
    /**
  *
  * @param fromFileStr 原圖片地址
  * @param saveToFileStr  生成縮略圖地址
  * @param formatWideth  生成圖片寬度
  * @param formatHeight  formatHeight高度
  */
    public void saveImageAsJpg(String fromFileStr, String saveToFileStr,
            int formatWideth, int formatHeight) throws Exception {
        BufferedImage srcImage;
        File saveFile = new File(saveToFileStr);
        File fromFile = new File(fromFileStr);
        srcImage = javax.imageio.ImageIO.read(fromFile); // construct image
        int imageWideth = srcImage.getWidth(null);
        int imageHeight = srcImage.getHeight(null);
        int changeToWideth = 0;
        int changeToHeight = 0;
        if (imageWideth > 0 && imageHeight > 0) {
            // flag=true;
            if (imageWideth / imageHeight >= formatWideth / formatHeight) {
                if (imageWideth > formatWideth) {
                    changeToWideth = formatWideth;
                    changeToHeight = (imageHeight * formatWideth) / imageWideth;
                } else {
                    changeToWideth = imageWideth;
                    changeToHeight = imageHeight;
                }
            } else {
                if (imageHeight > formatHeight) {
                    changeToHeight = formatHeight;
                    changeToWideth = (imageWideth * formatHeight) / imageHeight;
                } else {
                    changeToWideth = imageWideth;
                    changeToHeight = imageHeight;
                }
            }
        }

        srcImage = imageZoomOut(srcImage, changeToWideth, changeToHeight);
        ImageIO.write(srcImage, "JPEG", saveFile);
    }

    public BufferedImage imageZoomOut(BufferedImage srcBufferImage, int w, int h) {
        width = srcBufferImage.getWidth();
        height = srcBufferImage.getHeight();
        scaleWidth = w;

        if (DetermineResultSize(w, h) == 1) {
            return srcBufferImage;
        }
        CalContrib();
        BufferedImage pbOut = HorizontalFiltering(srcBufferImage, w);
        BufferedImage pbFinalOut = VerticalFiltering(pbOut, h);
        return pbFinalOut;
    }

    /**
     * 決定圖像尺寸
     */
    private int DetermineResultSize(int w, int h) {
        double scaleH, scaleV;
        scaleH = (double) w / (double) width;
        scaleV = (double) h / (double) height;
        // 需要判斷一下scaleH,scaleV,不做放大操作
        if (scaleH >= 1.0 && scaleV >= 1.0) {
            return 1;
        }
        return 0;

    } // end of DetermineResultSize()

    private double Lanczos(int i, int inWidth, int outWidth, double Support) {
        double x;

        x = (double) i * (double) outWidth / (double) inWidth;

        return Math.sin(x * PI) / (x * PI) * Math.sin(x * PI / Support)
                / (x * PI / Support);

    }

    private void CalContrib() {
        nHalfDots = (int) ((double) width * support / (double) scaleWidth);
        nDots = nHalfDots * 2 + 1;
        try {
            contrib = new double[nDots];
            normContrib = new double[nDots];
            tmpContrib = new double[nDots];
        } catch (Exception e) {
            System.out.println("init   contrib,normContrib,tmpContrib" + e);
        }

        int center = nHalfDots;
        contrib[center] = 1.0;

        double weight = 0.0;
        int i = 0;
        for (i = 1; i <= center; i++) {
            contrib[center + i] = Lanczos(i, width, scaleWidth, support);
            weight += contrib[center + i];
        }

        for (i = center - 1; i >= 0; i--) {
            contrib[i] = contrib[center * 2 - i];
        }

        weight = weight * 2 + 1.0;

        for (i = 0; i <= center; i++) {
            normContrib[i] = contrib[i] / weight;
        }

        for (i = center + 1; i < nDots; i++) {
            normContrib[i] = normContrib[center * 2 - i];
        }
    } // end of CalContrib()

    // 處理邊緣
    private void CalTempContrib(int start, int stop) {
        double weight = 0;

        int i = 0;
        for (i = start; i <= stop; i++) {
            weight += contrib[i];
        }

        for (i = start; i <= stop; i++) {
            tmpContrib[i] = contrib[i] / weight;
        }

    } // end of CalTempContrib()

    private int GetRedValue(int rgbValue) {
        int temp = rgbValue & 0x00ff0000;
        return temp >> 16;
    }

    private int GetGreenValue(int rgbValue) {
        int temp = rgbValue & 0x0000ff00;
        return temp >> 8;
    }

    private int GetBlueValue(int rgbValue) {
        return rgbValue & 0x000000ff;
    }

    private int ComRGB(int redValue, int greenValue, int blueValue) {

        return (redValue << 16) + (greenValue << 8) + blueValue;
    }

    // 行水平濾波
    private int HorizontalFilter(BufferedImage bufImg, int startX, int stopX,
            int start, int stop, int y, double[] pContrib) {
        double valueRed = 0.0;
        double valueGreen = 0.0;
        double valueBlue = 0.0;
        int valueRGB = 0;
        int i, j;

        for (i = startX, j = start; i <= stopX; i++, j++) {
            valueRGB = bufImg.getRGB(i, y);

            valueRed += GetRedValue(valueRGB) * pContrib[j];
            valueGreen += GetGreenValue(valueRGB) * pContrib[j];
            valueBlue += GetBlueValue(valueRGB) * pContrib[j];
        }

        valueRGB = ComRGB(Clip((int) valueRed), Clip((int) valueGreen),
                Clip((int) valueBlue));
        return valueRGB;

    } // end of HorizontalFilter()

    // 圖片水平濾波
    private BufferedImage HorizontalFiltering(BufferedImage bufImage, int iOutW) {
        int dwInW = bufImage.getWidth();
        int dwInH = bufImage.getHeight();
        int value = 0;
        BufferedImage pbOut = new BufferedImage(iOutW, dwInH,
                BufferedImage.TYPE_INT_RGB);

        for (int x = 0; x < iOutW; x++) {

            int startX;
            int start;
            int X = (int) (((double) x) * ((double) dwInW) / ((double) iOutW) + 0.5);
            int y = 0;

            startX = X - nHalfDots;
            if (startX < 0) {
                startX = 0;
                start = nHalfDots - X;
            } else {
                start = 0;
            }

            int stop;
            int stopX = X + nHalfDots;
            if (stopX > (dwInW - 1)) {
                stopX = dwInW - 1;
                stop = nHalfDots + (dwInW - 1 - X);
            } else {
                stop = nHalfDots * 2;
            }

            if (start > 0 || stop < nDots - 1) {
                CalTempContrib(start, stop);
                for (y = 0; y < dwInH; y++) {
                    value = HorizontalFilter(bufImage, startX, stopX, start,
                            stop, y, tmpContrib);
                    pbOut.setRGB(x, y, value);
                }
            } else {
                for (y = 0; y < dwInH; y++) {
                    value = HorizontalFilter(bufImage, startX, stopX, start,
                            stop, y, normContrib);
                    pbOut.setRGB(x, y, value);
                }
            }
        }

        return pbOut;

    } // end of HorizontalFiltering()

    private int VerticalFilter(BufferedImage pbInImage, int startY, int stopY,
            int start, int stop, int x, double[] pContrib) {
        double valueRed = 0.0;
        double valueGreen = 0.0;
        double valueBlue = 0.0;
        int valueRGB = 0;
        int i, j;

        for (i = startY, j = start; i <= stopY; i++, j++) {
            valueRGB = pbInImage.getRGB(x, i);

            valueRed += GetRedValue(valueRGB) * pContrib[j];
            valueGreen += GetGreenValue(valueRGB) * pContrib[j];
            valueBlue += GetBlueValue(valueRGB) * pContrib[j];
            // System.out.println(valueRed+"->"+Clip((int)valueRed)+"<-");
            //
            // System.out.println(valueGreen+"->"+Clip((int)valueGreen)+"<-");
            // System.out.println(valueBlue+"->"+Clip((int)valueBlue)+"<-"+"-->");
        }

        valueRGB = ComRGB(Clip((int) valueRed), Clip((int) valueGreen),
                Clip((int) valueBlue));
        // System.out.println(valueRGB);
        return valueRGB;

    } // end of VerticalFilter()

    private BufferedImage VerticalFiltering(BufferedImage pbImage, int iOutH) {
        int iW = pbImage.getWidth();
        int iH = pbImage.getHeight();
        int value = 0;
        BufferedImage pbOut = new BufferedImage(iW, iOutH,
                BufferedImage.TYPE_INT_RGB);

        for (int y = 0; y < iOutH; y++) {

            int startY;
            int start;
            int Y = (int) (((double) y) * ((double) iH) / ((double) iOutH) + 0.5);

            startY = Y - nHalfDots;
            if (startY < 0) {
                startY = 0;
                start = nHalfDots - Y;
            } else {
                start = 0;
            }

            int stop;
            int stopY = Y + nHalfDots;
            if (stopY > (int) (iH - 1)) {
                stopY = iH - 1;
                stop = nHalfDots + (iH - 1 - Y);
            } else {
                stop = nHalfDots * 2;
            }

            if (start > 0 || stop < nDots - 1) {
                CalTempContrib(start, stop);
                for (int x = 0; x < iW; x++) {
                    value = VerticalFilter(pbImage, startY, stopY, start, stop,
                            x, tmpContrib);
                    pbOut.setRGB(x, y, value);
                }
            } else {
                for (int x = 0; x < iW; x++) {
                    value = VerticalFilter(pbImage, startY, stopY, start, stop,
                            x, normContrib);
                    pbOut.setRGB(x, y, value);
                }
            }

        }

        return pbOut;

    } // end of VerticalFiltering()

    int Clip(int x) {
        if (x < 0)
            return 0;
        if (x > 255)
            return 255;
        return x;
    }
}

2.上傳文件到ftp

1)處理上傳文件到ftp的接口

package com.gy.common.attach;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import org.apache.commons.net.ftp.FTPClient;

/**
 * Simple to Introduction
 *
 * @category Simple to Introduction
 * @projectName common-attach
 * @package com.gy.common.attach.GYFtpClient.java
 * @className GYFtpClient
 * @description 上傳文件至ftp 接口類
 * @author hexy
 * @createDate 2014-10-13 下午12:04:32
 * @updateUser hexy
 * @updateDate 2014-10-13 下午12:04:32
 * @updateRemark 說明本次修改內容
 * @version v0.0.1
 */
public interface GYFtpClient {

    /**
     *
     * 連接到FTP服務器
     *
     * @return 是否連接成功
     * @throws IOException
     */
    public boolean connect() throws IOException;

    /**
     *
     * 連接到FTP服務器,端口默認爲21
     *
     * @param hostname
     *            主機名
     * @param username
     *            用戶名
     * @param password
     *            密碼
     * @return 是否連接成功
     * @throws IOException
     */
    public boolean connect(String hostname, String username, String password)
            throws IOException;

    /**
     *
     * 連接到FTP服務器
     *
     * @param hostname
     *            主機名
     * @param port
     *            端口
     * @param username
     *            用戶名
     * @param password
     *            密碼
     * @return 是否連接成功
     * @throws IOException
     */
    public boolean connect(String hostname, int port, String username,
            String password) throws IOException;

    /**
     * 斷開與遠程服務器的連接
     *
     * @throws IOException
     */
    public void disconnect() throws IOException;

    /**
     * 上傳文件到FTP服務器,支持目錄和斷點續傳
     *
     * @param subSystemName
     *            子系統名稱
     * @param local
     *            本地文件
     * @return 上傳結果
     * @throws Exception
     */
    public Map<Object, String> upload(String subSystemName, File local)
            throws Exception;

    /**
     * 斷點續傳
     *
     * @param remoteFile
     *            待上傳的文件名
     * @param localFile
     *            待上傳的文件
     * @param ftpClient
     *            
     * @param remoteSize
     *            
     * @return 上傳結果
     * @throws Exception
     */
    public UploadStatus uploadFile(String remoteFile, File localFile,
            FTPClient ftpClient, long remoteSize) throws IOException;
    /**
     *
     * 遞歸創建遠程服務器目錄
     *
     * @param remote
     *            遠程服務器文件絕對路徑
     * @param ftpClient
     *            FTPClient 對象
     * @return 目錄創建是否成功
     * @throws IOException
     */
    public UploadStatus CreateDirecroty(String remote, FTPClient ftpClient)
            throws IOException;

    public void setHostName(String string);

    public void setUserName(String string);

    public void setPassword(String string);

    public void setPort(int port);

}

2)處理上傳文件到ftp的實現類

  package com.gy.common.attach;

import static com.gy.common.utils.DateUtil.DATE_FORMAT;
import static com.gy.common.utils.DateUtil.DateToString;
import static com.gy.common.utils.DateUtil.getCurrentDate;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.Map;
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 com.gy.common.log.GyLogger;

/**   
 * Simple to Introduction
 * @category          Simple to Introduction
 * @projectName   common-attach
 * @package           com.gy.common.attach.GYFTPClientImpl.java
 * @className       GYFTPClientImpl
 * @description      上傳文件至ftp 實現類
 * @author              hexy
 * @createDate       2014-10-13 下午2:14:47  
 * @updateUser      hexy
 * @updateDate      2014-10-13 下午2:14:47
 * @updateRemark 說明本次修改內容
 * @version              v0.0.1
 */
public class GYFTPClientImpl implements GYFtpClient {

    protected GyLogger logger = GyLogger.getLogger(this.getClass());
    private FTPClient ftpClient = new FTPClient();
    boolean flag = true;
    private String hostName;
    private int port;
    private String password;
    private String userName;

    public GYFTPClientImpl(String hostName, String userName, String password) {
        super();
        this.hostName = hostName;
        this.userName = userName;
        this.password = password;
    }

    public GYFTPClientImpl(String hostName, int port, String userName,
            String password) {
        super();
        this.hostName = hostName;
        this.port = port;
        this.userName = userName;
        this.password = password;
    }

    public GYFTPClientImpl() {
    }

    @Override
    public boolean connect() throws IOException {
        return connect(hostName, port, userName, password);
    }

    @Override
    public boolean connect(String hostname, String username, String password)
            throws IOException {
        return this.connect(hostname, 0, username, password);
    }

    @Override
    public boolean connect(String hostname, int port, String username,
            String password) throws IOException {
        if (port == 0) {
            ftpClient.connect(hostname);
        } else {
            ftpClient.connect(hostname, port);
        }

        ftpClient.setControlEncoding("UTF-8");
        if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            if (ftpClient.login(username, password)) {
                return true;
            }
        }
        disconnect();
        return false;
    }

    @Override
    public void disconnect() throws IOException {
        if (ftpClient.isConnected()) {
            ftpClient.disconnect();
        }
    }

    /**
     *
     * @param file
     * 上傳的文件或文件夾
     * @throws Exception
     */
    @Override
    public Map<Object, String> upload(String subSystemName, File file)
            throws Exception {
        // 判斷subSystemName是否存在
        if (!SubSystemName.isSubSystemName(subSystemName)) {
            String msg = "No support subSystemName: " + subSystemName;
            logger.error(msg);
            throw new RuntimeException(msg);
        }
        if (flag) {
            // 創建apply目錄
            String path = subSystemName;
            ftpClient.makeDirectory(path);
            ftpClient.changeWorkingDirectory(path);
            // 創建日期目錄
            path = getDateForDir();
            ftpClient.makeDirectory(path);
            ftpClient.changeWorkingDirectory(path);
            flag = false;
        }
        Map<Object, String> result = new HashMap<Object, String>();
        if (file.isDirectory()) {
            ftpClient.makeDirectory(file.getName());
            ftpClient.changeWorkingDirectory(file.getName());
            String[] files = file.list();
            for (int i = 0; i < files.length; i++) {
                File subDir = new File(file.getPath() + "/" + files[i]);
                if (subDir.isDirectory()) {
                    upload(subSystemName, subDir);
                    ftpClient.changeToParentDirectory();
                } else {
                    File subFile = new File(file.getPath() + "/" + files[i]);
                    result = preUpload(subFile, subFile.getName());
                }
            }
        } else {
            File bfile = new File(file.getPath());
            result = preUpload(bfile, bfile.getName());
        }
        return result;
    }

    /**
     *
     * @param local
     * @param remote
     * 上傳文件
     * @throws Exception
     */
    private Map<Object, String> preUpload(File local, String remote)
            throws Exception {
        Map<Object, String> result = new HashMap<Object, String>();
        // 設置PassiveMode傳輸
        ftpClient.enterLocalPassiveMode();
        // 設置以二進制流的方式傳輸
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.setControlEncoding("UTF-8");
        // 對遠程目錄的處理
        String remoteFileName = remote;
        if (remote.contains("/")) {
            remoteFileName = remote.substring(remote.lastIndexOf("/") + 1);
            // 創建服務器遠程目錄結構,創建失敗直接返回
            if (CreateDirecroty(remote, ftpClient) == UploadStatus.Create_Directory_Fail) {
                result.put(UploadStatus.Create_Directory_Fail, hostName
                        + "/ftp/" + remote);
                return result;
            }
        }

        // 檢查遠程是否存在文件
        FTPFile[] files = ftpClient.listFiles(new String(remoteFileName
                .getBytes("UTF-8"), "ISO-8859-1"));
        if (files.length == 1) {
            long remoteSize = files[0].getSize();
            long localSize = local.length();
            if (remoteSize == localSize) {
                result.put(UploadStatus.File_Exits, hostName + "/ftp/" + remote);
                return result;
            } else if (remoteSize > localSize) {
                result.put(UploadStatus.Remote_Bigger_Local, hostName + "/ftp/"
                        + remote);
                return result;
            }
        } else {//遠程不存在則上傳
            uploadFile(remoteFileName, local, ftpClient, 0);
        }
        return result;
    }

    /**
     * 得到當前日期
     * @return
     */
    private String getDateForDir() {
        return DateToString(getCurrentDate(DATE_FORMAT), DATE_FORMAT);
    }

    /**
     * 斷點續傳
     */
    @Override
    public UploadStatus uploadFile(String remoteFile, File localFile,
            FTPClient ftpClient, long remoteSize) throws IOException {
        UploadStatus status;
        // 顯示進度的上傳
        long step = localFile.length() / 100;
        long process = 0;
        long localreadbytes = 0L;
        RandomAccessFile raf = new RandomAccessFile(localFile, "r");
        OutputStream out = ftpClient.appendFileStream(new String(remoteFile
                .getBytes("UTF-8"), "ISO-8859-1"));
        // 斷點續傳
        if (remoteSize > 0) {
            ftpClient.setRestartOffset(remoteSize);
            process = remoteSize / step;
            raf.seek(remoteSize);
            localreadbytes = remoteSize;
        }
        byte[] bytes = new byte[1024];
        int c;
        while ((c = raf.read(bytes)) != -1) {
            out.write(bytes, 0, c);
            localreadbytes += c;
            if (localreadbytes / step != process) {
                process = localreadbytes / step;
                System.out.println("上傳進度:" + process);
                // 彙報上傳狀態
            }
        }
        out.flush();
        raf.close();
        out.close();
        boolean result = ftpClient.completePendingCommand();
        if (remoteSize > 0) {
            status = result ? UploadStatus.Upload_From_Break_Success
                    : UploadStatus.Upload_From_Break_Failed;
        } else {
            status = result ? UploadStatus.Upload_New_File_Success
                    : UploadStatus.Upload_New_File_Failed;
        }
        return status;
    }

    /**
     * 創建遠程目錄
     */
    @Override
    public UploadStatus CreateDirecroty(String remote, FTPClient ftpClient)
            throws IOException {
        UploadStatus status = UploadStatus.Create_Directory_Success;
        String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
        if (!directory.equalsIgnoreCase("/")
                && !ftpClient.changeWorkingDirectory(new String(directory
                        .getBytes("UTF-8"), "ISO-8859-1"))) {
            // 如果遠程目錄不存在,則遞歸創建遠程服務器目錄
            int start = 0;
            int end = 0;
            if (directory.startsWith("/")) {
                start = 1;
            } else {
                start = 0;
            }
            end = directory.indexOf("/", start);
            while (true) {
                String subDirectory = new String(remote.substring(start, end)
                        .getBytes("UTF-8"), "ISO-8859-1");
                if (!ftpClient.changeWorkingDirectory(subDirectory)) {
                    if (ftpClient.makeDirectory(subDirectory)) {
                        ftpClient.changeWorkingDirectory(subDirectory);
                    } else {
                        System.out.println("創建目錄失敗");
                        return UploadStatus.Create_Directory_Fail;
                    }
                }

                start = end + 1;
                end = directory.indexOf("/", start);

                // 檢查所有目錄是否創建完畢
                if (end <= start) {
                    break;
                }
            }
        }
        return status;
    }

    @Override
    public void setHostName(String hostName) {
        this.hostName = hostName;
    }

    public String getHostName() {
        return hostName;
    }

    @Override
    public void setUserName(String userName) {
        this.userName = userName;
    }

    @Override
    public void setPassword(String password) {
        this.password = password;
    }

    public String getPassword() {
        return password;
    }

    public String getUserName() {
        return userName;
    }

    public int getPort() {
        return port;
    }

    @Override
    public void setPort(int port) {
        this.port = port;
    }

}

3)狀態描述類

  package com.gy.common.attach;

/**
 * Simple to Introduction
 *
 * @category Simple to Introduction
 * @projectName GYFtpClient
 * @package com.gy.common.ftp.UploadStatus.java
 * @className UploadStatus
 * @description 上傳文件至ftp 狀態描述類
 * @author hexy
 * @createDate 2014-10-10 上午11:10:36
 * @updateUser hexy
 * @updateDate 2014-10-10 上午11:10:36
 * @updateRemark 增加
 * @version v0.0.1
 */
public enum UploadStatus {
    /** 遠程服務器相應目錄創建失敗 */
    Create_Directory_Fail,
    /** 遠程服務器闖將目錄成功 */
    Create_Directory_Success,
    /** 上傳新文件成功 */
    Upload_New_File_Success,
    /** 上傳新文件失敗 */
    Upload_New_File_Failed,
    /** 文件已經存在 */
    File_Exits,
    /** 遠程文件大於本地文件 */
    Remote_Bigger_Local,
    /** 斷點續傳成功 */
    Upload_From_Break_Success,
    /** 斷點續傳失敗 */
    Upload_From_Break_Failed,
    /** 刪除遠程文件失敗 */
    Delete_Remote_Faild;
}




發佈了50 篇原創文章 · 獲贊 3 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章