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;
    }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值