1. 程式人生 > >sftp 下載 批量下載,單個下載,工具類

sftp 下載 批量下載,單個下載,工具類

fileToZIPAndUpload :

package com.utils;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpException;
import com.xmjr.constants.Constants;


public class fileToZIPAndUpload {
    private static Log log = LogFactory.getLog(fileToZIPAndUpload.class);



    /**
     * <p>
     * 從sftp批量下載資料<br>
     * </p>
     * <p>
     * -----版本-----變更日期-----責任人-----變更內容<br>
     * ─────────────────────────────────────<br>
     * @param fileNameList
     *            下載檔名稱list<String>
     * @param response
     * @return List<String>
     * @throws IOException
     *        </p>
     */
    public static List<String> batchDownload(List<String> fileNameList, HttpServletResponse response)
            throws IOException {


        List<String> resultList = new ArrayList<String>();
        ChannelSftp sftpConn = SftpClientUtil.connect(HOST, PORT, USER_NAME, PASSWORD);


        if (sftpConn == null) {
            resultList.add("下載服務連結失敗!");
            return resultList;
        }


        try {
            sftpConn.cd(UPLOAD_PATH);
        } catch (SftpException e) {
            resultList.add("資料目錄不存在!");
            return resultList;
        }
        File zipFile = new File("batchDownload_yingxiangziliao.zip");
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
        byte[] buf = new byte[1024];
        for (String fileName : fileNameList) {
            if (fileName != null) {
                InputStream in = null;
                try {
                    in = sftpConn.get(fileName);
                } catch (SftpException e) {
                    e.printStackTrace();
                    resultList.add(fileName + "下載失敗,資料不存在!");
                    return resultList;
                }
                out.putNextEntry(new ZipEntry(fileName));
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
            }
        }
        out.close();
        response.setHeader("Content-Disposition", "attachment;fileName="
                + new String(zipFile.getName().getBytes("GBK"), "ISO8859-1"));
        response.setContentType("application/x-download");
        OutputStream ot = response.getOutputStream();
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(zipFile));
        BufferedOutputStream bos = new BufferedOutputStream(ot);
        int length = 0;
        while ((length = bis.read(buf)) > 0) {
            bos.write(buf, 0, length);
        }
        bos.close();
        bis.close();
        ot.close();
        zipFile.delete();
        return resultList;
    }


    public static void deleteAndUpload(String yydk_pdf_reupload_path, String aplyno, String tranno)
            throws Exception {
        try {
            ChannelSftp sftpConn = SftpClientUtil.connect(HOST, PORT, USER_NAME, PASSWORD);
            // 需要刪除的壓縮包名
            String delZipName = aplyno + SPLIT_REGEX + tranno + SUFFIX;
            log.info("deleteAndUpload刪除: " + delZipName);
            // 刪除伺服器的壓縮檔案
            SftpClientUtil.delete(UPLOAD_PATH, delZipName, sftpConn);


            // 從應用伺服器上傳到伺服器
            String zipName = yydk_pdf_reupload_path + aplyno + SPLIT_REGEX + tranno + SUFFIX;
            log.info("deleteAndUpload上傳: " + zipName);
            boolean uploadToYyFlag = SftpClientUtil.upload(UPLOAD_PATH, zipName, sftpConn);
            if (!uploadToYyFlag) {
                log.error("上傳資料到有氧伺服器失敗!");
                throw new Exception("上傳資料到伺服器失敗!");
            }
        } catch (Exception e) {
            log.error("上傳影音資料出錯," + e.getMessage());
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }
    }


    /**
     * <p>
     * 從sftp單個下載資料<br>
     * </p>
     * <p>
     * -----版本-----變更日期-----責任人-----變更內容<br>
     *
     * @param fileName
     *            下載的檔名稱(包含字尾名)
     * @param response
     * @return String
     *        </p>
     */
    public static String download(String fileName, HttpServletResponse response) {
        ChannelSftp sftpConn = SftpClientUtil.connect(HOST, PORT, USER_NAME, PASSWORD);

        if (sftpConn == null) {
            return "連結失敗";
        }
        File zipFile = new File(fileName);
        byte[] buf = new byte[1024];


        try {
            sftpConn.cd(UPLOAD_PATH);
            InputStream in = sftpConn.get(fileName);


            response.setHeader("Content-Disposition", "attachment;fileName="
                    + new String(zipFile.getName().getBytes("GBK"), "ISO8859-1"));
            response.setContentType("application/x-download");
            OutputStream ot = response.getOutputStream();
            BufferedInputStream bis = new BufferedInputStream(in);
            BufferedOutputStream bos = new BufferedOutputStream(ot);
            int length = 0;
            while ((length = bis.read(buf)) > 0) {
                bos.write(buf, 0, length);
            }
            bos.close();
            bis.close();
            ot.close();
            zipFile.delete();
        } catch (SftpException e) {
            return "下載失敗,資料不存在!";
        } catch (Exception e) {
            e.printStackTrace();
            e.getMessage();
        } finally {
            sftpConn.quit();
        }
        return null;
    }


    /**
     * <p>
     * 補傳資料檔案<br>
     * </p>
     * <p>
     * -----版本-----變更日期-----責任人-----變更內容<br>
     *
     * @param yydk_pdf_reupload_path
     * @param aplyno
     * @param tranno
     * @throws Exception
     *             void
     *        </p>
     */
    public static void Upload(String yydk_pdf_reupload_path, String fileName) throws Exception {
        try {
            ChannelSftp sftpConn = SftpClientUtil.connect(HOST, PORT, USER_NAME, PASSWORD);


            // 從應用伺服器上傳到伺服器
            String zipName = _pdf_reupload_path + fileName;
            log.info("Upload上傳: " + zipName);
            boolean uploadToYyFlag = SftpClientUtil.upload(UPLOAD_PATH, zipName, sftpConn);
            if (!uploadToYyFlag) {
                log.error("上傳資料到伺服器失敗!");
                throw new Exception("上傳影音資料到有氧伺服器失敗!");
            }
        } catch (Exception e) {
            log.error("上傳資料出錯," + e.getMessage());
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }
    }


    /**
     * <p>
     * 申請傳送失敗後,重新命名流水號後,刪除原資料壓縮包,再按新的流水號打包上傳資料<br>
     * </p>
     * <p>
     * -----版本-----變更日期-----責任人-----變更內容<br>
     * ─────────────────────────────────────<br>
     * V1.0.0 2016年02月19日 hanfajie 初版<br>
     *
     * @param aplyno
     *            the 唯一申請編號.
     * @param suffix
     *            the 新流水號字尾當前時間戳.
     * @param oldTranno
     *            the 原流水號.
     * @throws Exception
     *             void
     *        </p>
     */
    public static void zipAndUpload(String aplyno, String suffix, String oldTranno)
            throws Exception {
        try {
            // 重新命名需要修改流水號的對應的資料
            ChannelSftp sftpConn = SftpClientUtil.connect(HOST, PORT, USER_NAME, PASSWORD);
            String oldZipName = aplyno + SPLIT_REGEX + oldTranno + SUFFIX;
            String newZipName = aplyno + SPLIT_REGEX + aplyno + suffix + SUFFIX;
            // 存在則重新命名成功,不存在或者其他異常則重新命名失敗,即重新上上傳
            boolean flag = SftpClientUtil.rename(UPLOAD_PATH, oldZipName, newZipName, sftpConn);
            if (!flag) {
                // 獲得影像資料路徑
                String imagePathString = XEDK_IMAGE_PATH + aplyno;
                // 判斷是否存在資料
                File file = new File(imagePathString);
                if (!file.exists() || !file.isDirectory() || file.listFiles().length == 0) {
                    throw new Exception("資料不存在,請檢查!");
                }
                // 壓縮資料路徑+名
                String zipName = XEDK_IMAGE_ZIP_PATH + aplyno + SPLIT_REGEX + aplyno + suffix
                        + SUFFIX;
                // 資料壓縮後不帶檔名
                ZIPUtil.createZip(imagePathString, zipName, 1);
                boolean uploadFlag = SftpClientUtil.upload(UPLOAD_PATH, zipName, sftpConn);
                if (!uploadFlag) {
                    log.error("上傳資料失敗!");
                    throw new Exception("上傳資料失敗!");
                }
            }
        } catch (Exception e) {
            log.error("上傳資料出錯," + e.getMessage());
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }
    }

}

呼叫:

 @Override
    public String download(String loanApplyIdArr, HttpServletResponse response) {
        // TODO Auto-generated method stub


        String[] loanApplyIdstr = loanApplyIdArr.split(",");
        Long[] loanApplyIds = new Long[loanApplyIdstr.length];
        int i = 0;
        for (String loanApplyId : loanApplyIdstr) {
            loanApplyIds[i++] = Long.parseLong(loanApplyId);
        }


        List<Map<String, Object>> loanApplyList = YYDKDaoMapper
                .selectLoanApplyInfoById(loanApplyIds);


        if (loanApplyList != null && !loanApplyList.isEmpty() && loanApplyList.size() > 0) {
            List<String> fileNameList = new ArrayList<String>();
            String fileName = null;
            for (Map<String, Object> loanApply : loanApplyList) {
                fileName = loanApply.get("aplyno").toString() + "_"
                        + loanApply.get("tranno").toString() + ".zip";
                fileNameList.add(fileName);
            }


            if (fileNameList != null && !fileNameList.isEmpty() && fileNameList.size() > 0) {
                if (fileNameList.size() == 1) {
                    return fileToZIPAndUpload.download(fileNameList.get(0), response);
                } else {
                    try {
                        List<String> resultList = fileToZIPAndUpload.batchDownload(fileNameList,
                                response);
                        if (resultList != null && !resultList.isEmpty() && resultList.size() > 0) {
                            return resultList.toString();
                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        return "資料批量下載失敗,請重試!";
                    }
                }
            }
        }
        return null;
    }