zoukankan      html  css  js  c++  java
  • springmvc+mybatis+html 下将查询数据以excell形式上传到ftp(上)

    package com.ninefbank.smallpay.admin.reconmgr.web;

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import java.io.UnsupportedEncodingException;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.servlet.ModelAndView;
    import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
    import com.github.miemiedev.mybatis.paginator.domain.PageList;
    import com.ninefbank.smallpay.admin.feemgr.dowload.ExeCreateFile;
    import com.ninefbank.smallpay.admin.logmgr.service.impl.LogServiceImpl;
    import com.ninefbank.smallpay.admin.reconmgr.service.IFinancialChannnelOrderService;
    import com.ninefbank.smallpay.admin.reconmgr.vo.FinancialChannelOrderVO;
    import com.ninefbank.smallpay.admin.util.FeeFlowExcelEnum;
    import com.ninefbank.smallpay.admin.util.FinancialChannelOrderEnum;
    import com.ninefbank.smallpay.admin.util.FinancialChannelOrderExcelView;
    import com.ninefbank.smallpay.admin.util.LogUtils;
    import com.ninefbank.smallpay.common.exception.ApplicationException;
    import com.ninefbank.smallpay.common.util.DateUtil;
    import com.ninefbank.smallpay.common.web.BaseController;

    /**
    * 金融渠道订单查询处理
    *
    * @author zhanghao
    *
    */
    @Controller
    @RequestMapping("fcOrder")
    public class FinancialChannelOrderController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(LogServiceImpl.class);
    @Autowired
    private IFinancialChannnelOrderService fcOrderService;

    /**
    * 金融渠道订单查询
    *
    * @param paramsMap
    * @return
    * @throws ApplicationException
    * @throws UnsupportedEncodingException
    */
    @RequestMapping(value = "/query", method = RequestMethod.POST)
    public @ResponseBody Map<String, Object> teTaskErrorInfoQuery(@RequestParam Map<String, Object> paramsMap)
    throws ApplicationException, UnsupportedEncodingException {
    Integer pageSize = Integer.parseInt(paramsMap.get("rows").toString());
    Integer pageNum = Integer.parseInt(paramsMap.get("page").toString());
    String channelName = paramsMap.get("channelName") == null ?
    null : paramsMap.get("channelName").toString();
    String channelCode = paramsMap.get("channelCode") == null ? null : paramsMap.get("channelCode").toString();
    String beginTime = paramsMap.get("beginTime") == null ? null : paramsMap.get("beginTime").toString();
    String endTime = paramsMap.get("endTime") == null ? null : paramsMap.get("endTime").toString();
    String envName = paramsMap.get("environmentName") == null ? null : paramsMap.get("environmentName").toString();
    String status = paramsMap.get("status") == null ? null : paramsMap.get("status").toString();
    String merNo = paramsMap.get("merNo") == null ? null : paramsMap.get("merNo").toString();
    String merName = paramsMap.get("merName") == null ? null : paramsMap.get("merName").toString();
    String payOrderNo = paramsMap.get("payOrderNo") == null ? null : paramsMap.get("payOrderNo").toString();
    String channelOrderNo = paramsMap.get("channelOrderNo") == null ? null : paramsMap.get("channelOrderNo").toString();
    paramsMap.clear();
    logger.info("环境参数:"+envName);
    PageBounds pageBounds = buildPageBounds(pageSize, pageNum, true);
    if (null != channelName && !"".equals(channelName)) {
    paramsMap.put("channelName", channelName);
    }
    if (null != channelCode && !"".equals(channelCode)) {
    paramsMap.put("channelCode", channelCode);
    }
    if (null != beginTime && !"".equals(beginTime)) {
    paramsMap.put("beginTime", beginTime);
    }
    if (null != endTime && !"".equals(endTime)) {
    paramsMap.put("endTime", endTime.replace("00:00:00", "23:59:59"));
    }
    if (null != envName && !"".equals(envName)) {
    paramsMap.put("envName", envName);
    if(envName.equals("1")){
    paramsMap.put("envName", "生产环境");
    }else if(envName.equals("2")){
    paramsMap.put("envName", "灰度环境");
    }else if(envName.equals("3")){
    paramsMap.put("envName", "测试环境");
    }else if(envName.equals("4")){
    paramsMap.put("envName", "开发环境");
    }
    logger.info("环境参数:envName.equals('1'):"+envName.equals("1")+
    ",envName.equals('2'):"+envName.equals("2")+
    ",envName.equals('3'):"+envName.equals("3")+
    ",envName.equals('4'):"+envName.equals("4"));
    }
    if (null != status && !"".equals(status)) {
    paramsMap.put("status", status);
    }
    if (null != merNo && !"".equals(merNo)) {
    paramsMap.put("merNo", merNo);
    }
    if (null != merName && !"".equals(merName)) {
    paramsMap.put("merName", merName);
    }
    if (null != payOrderNo && !"".equals(payOrderNo)) {
    paramsMap.put("payOrderNo", payOrderNo);
    }
    if (null != channelOrderNo && !"".equals(channelOrderNo)) {
    paramsMap.put("channelOrderNo", channelOrderNo);
    }
    PageList<FinancialChannelOrderVO> fcoList = fcOrderService.queryWithPage(paramsMap, pageBounds);
    return buildResult(pageSize, pageNum, fcoList);

    }

    /**
    * 金融渠道订单信息下载
    *
    * @param request
    * @param response
    * @return
    * @throws Exception
    */
    @RequestMapping(value = "/jxlExcel")
    public ModelAndView viewJxlExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String channelName = request.getParameter("channelName") == null ? null
    :new String(request.getParameter("channelName").toString().getBytes("iso-8859-1"),"UTF-8") ;
    String channelCode = request.getParameter("channelCode") == null ? null
    : request.getParameter("channelCode").toString();
    String beginTime = request.getParameter("bTime") == null ? null
    : request.getParameter("bTime").toString();
    String endTime = request.getParameter("eTime") == null ? null : request.getParameter("eTime").toString();
    String envName = request.getParameter("sysEnviroment") == null ? null
    : request.getParameter("sysEnviroment").toString();
    String status = request.getParameter("status") == null ? null
    : request.getParameter("status").toString();
    String merNo = request.getParameter("merNo") == null ? null
    : request.getParameter("merNo").toString();
    String payOrderNo = request.getParameter("payOrderNo") == null ? null
    : request.getParameter("payOrderNo").toString();
    String channelOrderNo = request.getParameter("channelOrderNo") == null ? null
    : request.getParameter("channelOrderNo").toString();
    Map<String, Object> params = new HashMap<String, Object>();
    if (null != channelName && !"".equals(channelName)) {
    params.put("channelName", channelName);
    }
    if (null != channelCode && !"".equals(channelCode)) {
    params.put("channelCode", channelCode);
    }
    if (null != beginTime && !"".equals(beginTime)) {
    params.put("beginTime", beginTime);
    }
    if (null != endTime && !"".equals(endTime)) {
    params.put("endTime", endTime.replace("00:00:00", "23:59:59"));
    }
    if (null != envName && !"".equals(envName)) {
    //params.put("envName", envName);
    if(envName.equals("1")){
    params.put("envName", "生产环境");
    }else if(envName.equals("2")){
    params.put("envName", "灰度环境");
    }else if(envName.equals("3")){
    params.put("envName", "测试环境");
    }else if(envName.equals("4")){
    params.put("envName", "开发环境");
    }
    }
    if (null != status && !"".equals(status)) {
    params.put("status", status);
    }
    if (null != merNo && !"".equals(merNo)) {
    params.put("merNo", merNo);
    }
    if (null != payOrderNo && !"".equals(payOrderNo)) {
    params.put("payOrderNo", payOrderNo);
    }
    if (null != channelOrderNo && !"".equals(channelOrderNo)) {
    params.put("channelOrderNo", channelOrderNo);
    }
    List<FinancialChannelOrderVO> fcOrderList = fcOrderService.downloadFile(params);
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("excelenum", FinancialChannelOrderEnum.FREEZEORDER);// 清分明细文件下载
    // excel模版
    StringBuffer fileName = new StringBuffer().append(DateUtil.parseDateTime(new Date(), null))
    .append("金融渠道订单查询记录.xls");
    model.put("list", fcOrderList);
    model.put("fileName", fileName.toString());// 文件名
    LogUtils.addLogInfo("金融渠道订单查询", "金融渠道订单下载", "金融渠道订单下载:" + model.get("fileName"), LogUtils.LOG_SUCCESS, null);
    return new ModelAndView(new FinancialChannelOrderExcelView(), model);

    }

    /**
    * 金融渠道订单信息下载
    *
    * @param request
    * @param response
    * @return
    * @throws Exception
    */
    @RequestMapping(value = "/jxlExcelNew")
    public @ResponseBody Map<String, Object> jxlExcelNew(@RequestParam Map<String, Object> param) throws Exception {
    String channelName = param.get("channelName")==null? "": new String(param.get("channelName").toString().getBytes("iso-8859-1"),"UTF-8");
    String channelCode = param.get("channelCode")==null? "": param.get("channelCode").toString();
    String beginTime = param.get("beginTime")==null? "": param.get("beginTime").toString();
    String endTime = param.get("endTime")==null? "": param.get("endTime").toString();
    String envName = param.get("sysEnviroment")==null? "": param.get("sysEnviroment").toString();
    String status = param.get("status")==null? "": param.get("status").toString();
    String merNo = param.get("merNo")==null? "": param.get("merNo").toString();
    String merName = param.get("merName")==null? "": param.get("merName").toString();
    String payOrderNo = param.get("payOrderNo")==null? "": param.get("payOrderNo").toString();
    String channelOrderNo = param.get("channelOrderNo")==null? "": param.get("channelOrderNo").toString();
    Map<String, Object> params = new HashMap<String, Object>();
    if (null != channelName && !"".equals(channelName)) {
    params.put("channelName", channelName);
    }
    if (null != channelCode && !"".equals(channelCode)) {
    params.put("channelCode", channelCode);
    }
    if (null != beginTime && !"".equals(beginTime)) {
    params.put("beginTime", beginTime);
    }
    if (null != endTime && !"".equals(endTime)) {
    params.put("endTime", endTime.replace("00:00:00", "23:59:59"));
    }
    if (null != envName && !"".equals(envName)) {
    //params.put("envName", envName);
    if(envName.equals("1")){
    params.put("envName", "生产环境");
    }else if(envName.equals("2")){
    params.put("envName", "灰度环境");
    }else if(envName.equals("3")){
    params.put("envName", "测试环境");
    }else if(envName.equals("4")){
    params.put("envName", "开发环境");
    }
    }
    if (null != status && !"".equals(status)) {
    params.put("status", status);
    }
    if (null != merNo && !"".equals(merNo)) {
    params.put("merNo", merNo);
    }
    if (null != merName && !"".equals(merName)) {
    params.put("merName", merName);
    }
    if (null != payOrderNo && !"".equals(payOrderNo)) {
    params.put("payOrderNo", payOrderNo);
    }
    if (null != channelOrderNo && !"".equals(channelOrderNo)) {
    params.put("channelOrderNo", channelOrderNo);
    }
    // List<FinancialChannelOrderVO> fcOrderList = fcOrderService.downloadFile(params);
    // Map<String, Object> model = new HashMap<String, Object>();
    // model.put("excelenum", FinancialChannelOrderEnum.FREEZEORDER);// 清分明细文件下载
    // excel模版
    StringBuffer fileName = new StringBuffer().append(DateUtil.parseDateTime(new Date(), null))
    .append("金融渠道订单查询记录.xlsx");

    ExecutorService single = Executors.newSingleThreadExecutor();
    single.submit(new ExeCreateFile(params, fileName.toString(), "fcOrderService", FeeFlowExcelEnum.CHANNALEORDERQUERRY, "channel/orderQuerry/"));
    single.shutdown();

    return buildResult(fileName.toString());
    // model.put("list", fcOrderList);
    // model.put("fileName", fileName.toString());// 文件名
    // LogUtils.addLogInfo("金融渠道订单查询", "金融渠道订单下载", "金融渠道订单下载:" + model.get("fileName"), LogUtils.LOG_SUCCESS, null);
    // return new ModelAndView(new FinancialChannelOrderExcelView(), model);

    }
    }

    以下是 ExeCreateFile.java 在主线程之外新起一个线程单独执行将数据库中数据分批查询以excell 形式下载到ftp上,
      1 package com.ninefbank.smallpay.admin.feemgr.dowload;
      2 
      3 import java.io.File;
      4 import java.io.FileOutputStream;
      5 import java.lang.reflect.Method;
      6 import java.util.ArrayList;
      7 import java.util.List;
      8 import java.util.Map;
      9 
     10 import org.slf4j.Logger;
     11 import org.slf4j.LoggerFactory;
     12 
     13 import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
     14 import com.github.miemiedev.mybatis.paginator.domain.PageList;
     15 import com.github.miemiedev.mybatis.paginator.domain.Paginator;
     16 import com.ninefbank.smallpay.admin.common.Ftp;
     17 import com.ninefbank.smallpay.admin.util.AppConstants;
     18 import com.ninefbank.smallpay.admin.util.CommonExcelView;
     19 import com.ninefbank.smallpay.admin.util.DataBaseConst;
     20 import com.ninefbank.smallpay.admin.util.FeeFlowExcelEnum;
     21 import com.ninefbank.smallpay.admin.util.FtpUtils;
     22 import com.ninefbank.smallpay.common.util.DateUtil;
     23 import com.ninefbank.smallpay.common.util.SpringContextHolder;
     24 import com.ninefbank.smallpay.common.vo.FtpRequest;
     25 
     26 public class ExeCreateFile implements Runnable {
     27     private static Logger logger = LoggerFactory.getLogger(ExeCreateFile.class);
     28     private Map<String, Object> params;
     29     private String fileName;
     30     private String queryBeanName;
     31     private FeeFlowExcelEnum feeFlowExcelEnum;
     32     private String newFilePath;
     33     
     34     /**
     35      * @param params:查询参数
     36      * @param fileName:生成excel文件名称
     37      * @param queryBeanName:分页查询的bean name
     38      * @param feeFlowExcelEnum:excel模板
     39      * @param newFilePath:生成的excel放到FTP上追加路径
     40      */
     41     public ExeCreateFile(Map<String, Object> params, String fileName, String queryBeanName, FeeFlowExcelEnum feeFlowExcelEnum, String newFilePath){
     42         this.params = params;
     43         this.fileName = fileName;
     44         this.queryBeanName = queryBeanName;
     45         this.feeFlowExcelEnum = feeFlowExcelEnum;
     46         this.newFilePath = newFilePath;
     47     }
     48 
     49     @Override
     50     public void run() {
     51         try {
     52             int rows = AppConstants.DOWNLOAD_PAGE_SIZE;
     53             int page = 1;
     54             PageBounds pageBounds = buildPageBounds(rows, page, true);
     55             Object obj = SpringContextHolder.getBean(queryBeanName);
     56             Class cls = obj.getClass();
     57             Method mth = cls.getMethod("queryWithPage", Map.class, PageBounds.class);
     58             PageList list = (PageList)mth.invoke(obj, params, pageBounds);
     59             Paginator paginator = list.getPaginator();
     60             if(list==null || list.size()==0){
     61                 logger.info("下载数据为空,不予生成文件,请求参数:{}", new Object[]{params});
     62                 return;
     63             }
     64             FtpUtils.createDir(DataBaseConst.TEMP_FEE_CREATE_PATH);
     65             
     66             if(paginator != null){
     67                 
     68                 int totalPages = paginator.getTotalPages();
     69                 //如果超过10万条则分book
     70                 if(totalPages>20){
     71                     int bookSize = 0;
     72                     if(totalPages%20==0){
     73                         bookSize = totalPages/20;
     74                     }else{
     75                         bookSize = totalPages/20+1;
     76                     }
     77                     List<String> fileNameList = new ArrayList<String>();
     78                     for(int i=0;i<bookSize;i++){
     79                         CommonExcelView cev = new CommonExcelView();
     80                         String branchFileName = createBranchFileName(fileName,i);
     81                         File file = new File(DataBaseConst.TEMP_FEE_CREATE_PATH + branchFileName);
     82                         cev.init(new FileOutputStream(file), feeFlowExcelEnum);
     83                         if(i==0){
     84                             cev.buildExcelDocument(list);
     85                         }
     86                         logger.info("分页总数为:"+totalPages);
     87                         for(; page <= 20*(i+1);page++){
     88                             if(page==1){page++;}
     89                             logger.info("总共页数:【{}】;当前页数:【{}】;当前文件名:【{}】", new Object[]{totalPages, page,branchFileName});
     90                             pageBounds = buildPageBounds(rows, page, true);
     91                             logger.info("pageBounds 参数为:rows【{}】,page【{}】",rows,page);
     92                             list = (PageList)mth.invoke(obj, params, pageBounds);
     93                             
     94                             cev.buildExcelDocument(list);
     95                         }
     96                         cev.closed();
     97                         
     98                         logger.info("创建excel【{}】成功", new Object[]{branchFileName});
     99                         
    100                         //将生成的文件上传到FTP
    101                         String localPath = DataBaseConst.TEMP_FEE_CREATE_PATH + branchFileName;
    102                         FtpRequest req = new FtpRequest();
    103                         req.setIp(DataBaseConst.FTP_FEE_IP);
    104                         req.setPort(DataBaseConst.FTP_FEE_PORT);
    105                         req.setUserName(DataBaseConst.FTP_FEE_USERNAME);
    106                         req.setPwd(DataBaseConst.FTP_FEE_PASSWORD);
    107                         req.setDownloadPath(DataBaseConst.FTP_FEE_PATH + newFilePath);
    108                         req.setFileName(branchFileName);
    109                         req.setLocalPath(localPath);
    110                         
    111                         FtpUtils.uploadFTP(req);
    112                         Ftp f=new Ftp();
    113                         f.setIpAddr(DataBaseConst.FTP_FEE_IP);
    114                         f.setUserName(DataBaseConst.FTP_FEE_USERNAME);
    115                         f.setPwd(DataBaseConst.FTP_FEE_PASSWORD);
    116                         String currDate8 = DateUtil.getCurrentDateTime("yyyyMMdd");
    117                         String ftpPath = DataBaseConst.FTP_FEE_PATH + newFilePath + currDate8 + "/";
    118 //                        FtpUtils.startDown(f, "e:/", ftpPath,req);
    119                         logger.info("将文件excel【{}】上传到FTP成功", new Object[]{branchFileName});
    120                         
    121                         File localFile = new File(localPath);
    122                         if(localFile.exists()){
    123                             boolean flg = localFile.delete();
    124                             logger.info("删除临时目录文件【{}】" + (flg?"成功":"失败"), new Object[]{localPath});
    125                         }
    126                     }
    127                      
    128                 }else{
    129                     CommonExcelView cev = new CommonExcelView();
    130                     File file = new File(DataBaseConst.TEMP_FEE_CREATE_PATH + fileName);
    131                     if(!file.exists()){
    132                         file.createNewFile();
    133                     }
    134                     cev.init(new FileOutputStream(file), feeFlowExcelEnum);
    135                     cev.buildExcelDocument(list);
    136                     
    137                     if(paginator != null){
    138                         
    139                         if(totalPages > 1){
    140                             for(page++; page <= totalPages; page++){
    141                                 logger.info("总共页数:【{}】;当前页数:【{}】", new Object[]{totalPages, page});
    142                                 pageBounds = buildPageBounds(rows, page, true);
    143                                 
    144                                 list = (PageList)mth.invoke(obj, params, pageBounds);
    145                                 
    146                                 cev.buildExcelDocument(list);
    147                             }
    148                         }
    149                     }
    150                     
    151                     cev.closed();
    152                     
    153                     logger.info("创建excel【{}】成功", new Object[]{fileName});
    154                     
    155                     //将生成的文件上传到FTP
    156                     String localPath = DataBaseConst.TEMP_FEE_CREATE_PATH + fileName;
    157                     FtpRequest req = new FtpRequest();
    158                     req.setIp(DataBaseConst.FTP_FEE_IP);
    159                     req.setPort(DataBaseConst.FTP_FEE_PORT);
    160                     req.setUserName(DataBaseConst.FTP_FEE_USERNAME);
    161                     req.setPwd(DataBaseConst.FTP_FEE_PASSWORD);
    162                     req.setDownloadPath(DataBaseConst.FTP_FEE_PATH + newFilePath);
    163                     req.setFileName(fileName);
    164                     req.setLocalPath(localPath);
    165                     
    166                     FtpUtils.uploadFTP(req);
    167                     
    168                     logger.info("将文件excel【{}】上传到FTP成功", new Object[]{fileName});
    169                     Ftp f=new Ftp();
    170                     f.setIpAddr(DataBaseConst.FTP_FEE_IP);
    171                     f.setUserName(DataBaseConst.FTP_FEE_USERNAME);
    172                     f.setPwd(DataBaseConst.FTP_FEE_PASSWORD);
    173                     String currDate8 = DateUtil.getCurrentDateTime("yyyyMMdd");
    174                     String ftpPath = DataBaseConst.FTP_FEE_PATH + newFilePath + currDate8 + "/";
    175                     FtpUtils.startDown(f, "e:/", ftpPath,req);
    176                     
    177                     File localFile = new File(localPath);
    178                     if(localFile.exists()){
    179                         boolean flg = localFile.delete();
    180                         logger.info("删除临时目录文件【{}】" + (flg?"成功":"失败"), new Object[]{localPath});
    181                     }
    182                 }
    183                 
    184                 
    185                 
    186                 
    187             }
    188             
    189             
    190             
    191         } catch (Exception e) {
    192             logger.error("创建excel异常,fileName:{}", new Object[]{fileName}, e);
    193         }
    194         
    195     }
    196     
    197     private String createBranchFileName(String fileName, int i) {
    198         String fileNameNoSuffix = fileName.substring(0,fileName.indexOf("."));
    199         String fileNameSuffix = fileName.substring(fileName.indexOf("."),fileName.length());
    200         logger.info("创建book名-无后缀:"+fileNameNoSuffix+",后缀:"+fileNameSuffix);
    201         String newBranchFileName = fileNameNoSuffix+"_"+i+fileNameSuffix;
    202         logger.info("创建book名:"+newBranchFileName);
    203         return newBranchFileName;
    204         
    205     }
    206 
    207     private PageBounds buildPageBounds(Integer pageSize, Integer currentPageNum, Boolean isContainsTotalCount){
    208         if(null == pageSize){
    209             pageSize = 10;
    210         }
    211         if(null == currentPageNum){
    212             currentPageNum = 1;
    213         }
    214         if(null == isContainsTotalCount){
    215             isContainsTotalCount = true;
    216         }
    217         PageBounds pageBounds = new PageBounds();
    218         pageBounds.setPage(currentPageNum);
    219         pageBounds.setLimit(pageSize);
    220         pageBounds.setContainsTotalCount(isContainsTotalCount);
    221         return pageBounds;
    222     }
    223     
    224 }

    以下是ftp工具类:

      1 package com.ninefbank.smallpay.admin.util;
      2 
      3 import java.io.BufferedOutputStream;
      4 import java.io.File;
      5 import java.io.FileInputStream;
      6 import java.io.FileOutputStream;
      7 import java.io.IOException;
      8 
      9 import org.apache.commons.lang3.StringUtils;
     10 import org.apache.commons.net.ftp.FTPClient;
     11 import org.apache.commons.net.ftp.FTPFile;
     12 import org.slf4j.Logger;
     13 import org.slf4j.LoggerFactory;
     14 
     15 import com.jcraft.jsch.Channel;
     16 import com.jcraft.jsch.ChannelSftp;
     17 import com.jcraft.jsch.JSch;
     18 import com.jcraft.jsch.Session;
     19 import com.ninefbank.smallpay.common.util.DateUtil;
     20 import com.ninefbank.smallpay.common.vo.FtpRequest;
     21 
     22 public class FtpUtils {
     23     private static Logger logger = LoggerFactory.getLogger(FtpUtils.class);
     24     
     25     public static boolean uploadFTP(FtpRequest reqs){
     26         boolean suc = false;
     27         String ip = reqs.getIp();
     28         int port = Integer.parseInt(reqs.getPort());
     29         String userName = reqs.getUserName();
     30         String userPwd = reqs.getPwd();
     31         String path = reqs.getDownloadPath();
     32         String fileName = reqs.getFileName();
     33         String localPath = reqs.getLocalPath();
     34         FTPClient ftpClient = new FTPClient();
     35         FileInputStream fis = null;
     36         
     37         try {
     38             // 1.连接服务器
     39             ftpClient.connect(ip, port);
     40             // 登录
     41             ftpClient.login(userName, userPwd);
     42             ftpClient.setControlEncoding("UTF-8");
     43             // 设置传输协议
     44             ftpClient.enterLocalPassiveMode();
     45             ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
     46             
     47             if (path != null && path.length() > 0) {
     48                 String currDate8 = DateUtil.getCurrentDateTime("yyyyMMdd");
     49                 path = path + currDate8 + "/";
     50                 if(!createFTPDir(path, ftpClient)){
     51                     return suc;
     52                 }
     53                 ftpClient.changeWorkingDirectory(path);
     54                 File file = new File(localPath);
     55                 fis = new FileInputStream(file);
     56                 suc = ftpClient.storeFile(new String(file.getName().getBytes("GBK"), "iso-8859-1"), fis);
     57                 logger.info(file.getName() + "上传" + (suc?"成功":"失败"));
     58             }
     59             
     60             
     61         } catch (Exception e) {
     62             logger.error(fileName + "上传失败", e);
     63         } finally {
     64             try {
     65                 if(null != fis) {
     66                     fis.close();
     67                     ftpClient.logout();
     68                 }
     69                 if(ftpClient.isConnected()){
     70                     ftpClient.disconnect();
     71                 }
     72             } catch (Exception e) {
     73                 logger.error("关闭连接/流异常", e);
     74             }
     75         }
     76         
     77         return suc;
     78     }
     79     
     80     private static boolean createFTPDir(String remote, FTPClient ftpClient) {
     81         boolean flag = false;
     82         try {
     83             String dir = remote;
     84             if("/".equalsIgnoreCase(dir) || ftpClient.changeWorkingDirectory(dir)){
     85                 flag = true;
     86                 
     87             }else{
     88                 int start = 0;
     89                 int end = 0;
     90                 if (dir.startsWith("/")) {
     91                     start = 1;
     92                 } else {
     93                     start = 0;
     94                 }
     95                 end = dir.indexOf("/", start);
     96                 String path = "";
     97                 String paths = "";
     98                 while (true) {
     99 
    100                     String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
    101                     path = path + "/" + subDirectory;
    102                     if (!existFile(path, ftpClient)) {
    103                         if (ftpClient.makeDirectory(subDirectory)) {
    104                             ftpClient.changeWorkingDirectory(subDirectory);
    105                         } else {
    106                             logger.info("创建目录[" + subDirectory + "]失败,该目录已存在");
    107                             ftpClient.changeWorkingDirectory(subDirectory);
    108                         }
    109                     } else {
    110                         ftpClient.changeWorkingDirectory(subDirectory);
    111                     }
    112 
    113                     paths = paths + "/" + subDirectory;
    114                     start = end + 1;
    115                     end = dir.indexOf("/", start);
    116                     // 检查所有目录是否创建完毕
    117                     if (end <= start) {
    118                         break;
    119                     }
    120                 }
    121                 flag = true;
    122             }
    123             
    124         } catch (Exception e) {
    125             logger.error("创建FTP路径异常,路径信息:{}", new Object[]{remote}, e);
    126         }
    127         
    128         return flag;
    129     }
    130     
    131     //判断ftp服务器文件是否存在    
    132     private static boolean existFile(String path, FTPClient ftpClient) throws IOException{
    133         boolean flag = false;
    134         FTPFile[] ftpFileArr = ftpClient.listFiles(path);
    135         if (ftpFileArr.length > 0) {
    136             flag = true;
    137         }
    138         
    139         return flag;
    140     }
    141 
    142     /**
    143      * downLoadFileFTP(使用ftp协议)<br/>
    144      * @param reqs
    145      * @return 
    146      * String
    147      * @exception
    148      * @since  1.0.0
    149     */
    150     public static boolean downLoadFileFTP(FtpRequest reqs){
    151         String ip = reqs.getIp();
    152         int port = Integer.parseInt(reqs.getPort());
    153         String userName = reqs.getUserName();
    154         String userPwd = reqs.getPwd();
    155         String path = reqs.getDownloadPath();
    156         String fileName = reqs.getFileName();
    157         String localPath = reqs.getLocalPath();
    158         FTPClient ftpClient = new FTPClient();
    159         BufferedOutputStream outStream = null;
    160         boolean success = false;
    161         try {
    162              // 1.连接服务器
    163             ftpClient.connect(ip, port);
    164             // 登录
    165             ftpClient.login(userName, userPwd);
    166             ftpClient.setControlEncoding("UTF-8");
    167             // 设置传输协议
    168             ftpClient.enterLocalPassiveMode();
    169             ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
    170             ftpClient.setListHiddenFiles(true);
    171             
    172             String localDir = localPath.substring(0, localPath.lastIndexOf('/') + 1);
    173             createDir(localDir);
    174             
    175             File file = new File(localPath);
    176             if(!file.exists()){
    177                 boolean flag = file.createNewFile();
    178                 logger.info("创建本地路径结果:" + flag);
    179             }
    180             
    181             if (path != null && path.length() > 0) {
    182                 ftpClient.changeWorkingDirectory(path);
    183             }
    184             
    185              outStream = new BufferedOutputStream(new FileOutputStream(localPath));
    186              logger.info("开始下载" + fileName);
    187              success = ftpClient.retrieveFile(fileName, outStream);
    188              if(success){
    189                  logger.info("文件成功下载到" + localPath);
    190                  
    191              }else{
    192                  logger.error(fileName + "下载失败");
    193              }
    194         } catch (Exception e) {
    195             logger.error(fileName + "下载失败", e);
    196         }finally {
    197               try {
    198                   if (null != outStream) {
    199                      outStream.flush();
    200                      outStream.close();
    201                      ftpClient.logout();
    202                   }
    203                  if(ftpClient.isConnected()){
    204                      ftpClient.disconnect();
    205                  }
    206               } catch (Exception e) {
    207                   logger.error("关闭连接/流异常", e);
    208               }
    209         }
    210         
    211         return success;
    212     }
    213     
    214     /**
    215      * downLoadFileSFTP(使用sftp协议)<br/>
    216      * @param reqs
    217      * @return 
    218      * String
    219      * @exception
    220      * @since  1.0.0
    221     */
    222     public static boolean downLoadFileSFTP(FtpRequest reqs){
    223         String ip = reqs.getIp();
    224         String port = reqs.getPort();
    225         String userName = reqs.getUserName();
    226         String userPwd = reqs.getPwd();
    227         String path = reqs.getDownloadPath();
    228         String fileName = reqs.getFileName();
    229         String localPath = reqs.getLocalPath();
    230         Session session = null;
    231         Channel channel = null;
    232         JSch jsch = new JSch();
    233         boolean success = false;
    234         
    235         try {
    236              // 1.连接服务器
    237             if(StringUtils.isEmpty(port)){
    238                 //连接服务器,采用默认端口
    239                 session = jsch.getSession(userName, ip);
    240             }else{
    241                 //采用指定的端口连接服务器
    242                 session = jsch.getSession(userName, ip , Integer.parseInt(port));
    243             }
    244             //如果服务器连接不上,则抛出异常
    245             if (session == null) {
    246                 logger.error("下载文件异常 session is null");
    247                 return success;
    248             }
    249             
    250             //设置登陆主机的密码
    251             session.setPassword(userPwd);
    252             //设置第一次登陆的时候提示,可选值:(ask | yes | no)
    253             session.setConfig("StrictHostKeyChecking", "no");
    254             //设置登陆超时时间
    255             session.connect(30000);
    256             
    257             //创建sftp通信通道
    258             channel = session.openChannel("sftp");
    259             channel.connect(1000);
    260             ChannelSftp sftp = (ChannelSftp)channel;
    261             
    262             //进入服务器指定的文件夹
    263             sftp.cd(path);
    264             
    265             String localDir = localPath.substring(0, localPath.lastIndexOf('/') + 1);
    266             createDir(localDir);
    267             
    268             File file = new File(localPath);
    269             if(!file.exists()){
    270                 boolean flag = file.createNewFile();
    271                 logger.info("创建本地路径结果:" + flag);
    272             }
    273             //下载文件
    274             sftp.get(fileName, new FileOutputStream(file));
    275             logger.info("文件成功下载到" + localPath);
    276             
    277             success = true;
    278             
    279         } catch (Exception e) {
    280             logger.error(fileName + "下载失败", e);
    281         }finally {
    282             session.disconnect();
    283             channel.disconnect();
    284         }
    285         
    286         return success;
    287     }
    288     
    289     public static boolean createDir(String destDirName) {
    290         File dir = new File(destDirName);
    291         if (dir.exists()) {
    292             logger.info("创建目录" + destDirName + "失败,目标目录已经存在");
    293             return false;
    294         }
    295         if (!destDirName.endsWith(File.separator)) {
    296             destDirName = destDirName + File.separator;
    297         }
    298         //创建目录  
    299         if (dir.mkdirs()) {
    300             logger.info("创建目录" + destDirName + "成功!");
    301             return true;
    302         } else {
    303             logger.info("创建目录" + destDirName + "失败!");
    304             return false;
    305         }
    306     }
    307     
    308 }

    excell 文件每十万一个文件,上传完毕之后删掉临时目录下的文件(部署的服务器app路径下)

    忘了写最前面的html:

    taskErrorInfoForFinancialChannelOrder.html
  • 相关阅读:
    [转]开源游戏AI引擎列表与游戏中的人工智能
    [转]刨根问底!曲面细分技术到底是个啥?
    [转]link time code generation
    [转]PythonQt
    [转]Free Game Development Libraries
    Java虚拟机(二):垃圾回收算法 时间
    Java虚拟机(一):JVM的运行机制 时间
    Java虚拟机(四):常用JVM配置参数 时间
    Java虚拟机(三):垃圾收集器 时间
    mov offset和lea的区别
  • 原文地址:https://www.cnblogs.com/sailormoon/p/6950716.html
Copyright © 2011-2022 走看看