zoukankan      html  css  js  c++  java
  • exacle文件上传

    @RequestMapping(value = "/upload/uploadFileBankExcel", method = RequestMethod.POST)
        public String uploadExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws ParseException {
            Map map=request.getParameterMap();
            String dataStr = request.getParameter("dataStr");
            //文件类型
            String fileTypeReal = FilesUtils.GetFileType(file.getOriginalFilename());
            //文件路径模版
            String filePath = contractCodePath + "uploadFile";
            //uuid文件名称
            String fileUuid = FilesUtils.GetUUIDFileName(fileTypeReal);
            //上传文件名称
            String fileName = file.getOriginalFilename();
    
            Map dataMap = JsonPluginsUtil.jsonToMap(dataStr);
            //接受前台传过来的产品名称与产品代码
            String productType = dataMap.get("productType").toString();
            String productName = dataMap.get("name").toString();
            Integer projetId=Integer.parseInt(productType);
            Object date1 = dataMap.get("minTimes");
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    
            Date date = formatter.parse(date1.toString());
            //通过文件名查询数据条数
            int uploadFileBankCount = uploadFileBankService.selectUploadFileCount(fileName);
            if (uploadFileBankCount != 0) {
                uploadFileBankService.deleteUploadFileBankByFileName(fileName);
                logger.info(fileName + "重复,删除数据");
            }
            //文件上传
            boolean uploadFlag = FilesUtils.uploadFileByPathAndName(file, filePath, fileUuid);
    
            String res = null;
            //文件保存的数据库表
            UploadFileBank uploadFile = new UploadFileBank();
            uploadFile.setCreateTime(new Date());
            uploadFile.setFileName(fileName);
            uploadFile.setFileUrl(fileUuid);
            uploadFile.setProjectId(projetId);
            uploadFile.setProjectName(productName);
            //根据产品代码 查询产品ID与产品名称
            // 若上传成功
            if (uploadFlag) {
                //上传文件的总路径
                String path = filePath + "/" + fileUuid;
                String tempPath = contractCodePath;
                InputStream inputStream = null;
                Workbook workbook = null;
                try {
                    inputStream = new FileInputStream(path);
                    workbook = ExcelUtils.isXlsOrXlsx(inputStream, path);
                } catch (Exception e) {
                    e.printStackTrace();
                    return failure(2, "上传失败,请检查上传内容");
                } finally {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                //uploadFile.setFileId();
                //模板路径
                tempPath += "bank.xls";
                //上传表数据入库
                res = getRepaymentPlan(workbook, path, tempPath, date);
    
                if ("成功".equals(res)) {
                    uploadFile.setUploadState("上传成功");
                } else {
                    uploadFile.setUploadState("上传异常");
                    uploadFile.setRemark(res);
                }
            } else {
                uploadFile.setUploadState("上传失败");
                uploadFile.setRemark("请核对上传模版");
            }
            uploadFileBankService.addUploadFileBank(uploadFile);
            return success();
        }
    
    
        /**
         * Title: getRepaymentPlan
         * Description: 银行还款计划表入库
         *
         * @author: 席清宁
         * @Date: 2019/07/11 17:22
         */
        public String getRepaymentPlan(Workbook workbook, String path, String tempPath,Date date) {
            try {
                if (workbook != null) {
    
                    List<RepaymentBankModel> repaymentBankModels = new ArrayList<>();
                    //遍历上传Excel的sheet和模板的sheet1对比如果相同不进行处理
                    for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
                        //
                        boolean flag = ExcelUtils.judgeExcelModel(path, tempPath, numSheet, 0);
                        //判断表头是否存在true存在
                        if(flag == false ){
                            return "银行还款计划表有错误,请检查是否是需要的文件,或者查看是否有多余的sheet,如果有删除多余的sheet删除后重新上传";
                        }
                        repaymentBankModels = ExcelUtils.readExcelByRow(path, numSheet, 1, RepaymentBankModel.class, getMap());
                        //更新数据库表
                        String res=updateFileBank(repaymentBankModels,date);
                        //判断是否有异常消息
                        if(StringUtils.isNotBlank(res)){
                            return res;
                        }
                    }
    
                }
            } catch (Exception e) {
                e.printStackTrace();
                return "上传失败";
            }
            return "成功";
        }
        /**
         *
         */
        private String updateFileBank(List<RepaymentBankModel> repaymentBankModels ,Date date) throws ParseException {
           //处理数据
            List<Map> list = new ArrayList<>();
            String res = null;
            StringBuilder news = new StringBuilder();
            for(RepaymentBankModel repaymentBankModel :repaymentBankModels){
                System.out.println("处理:" + repaymentBankModel.getName() + "身份证号为:"+ repaymentBankModel.getIdnumber()+" 还款信息");
                Repayment repayment = new Repayment();
                String id=repaymentBankModel.getIdnumber();
                //跟据身份证号查询客户ID
                String customerId = customerService.selectCustomerByNo(id);
                if(customerId==null){
                    news.append("客户"+repaymentBankModel.getName() + "身份证号为:"+ repaymentBankModel.getIdnumber()+"信息不存在");
                    continue;
                }
                logger.info("客户ID"+customerId);
                repayment.setCustomerId(customerId);
                repayment.setPayDate(DateUtils.getDateFromString(repaymentBankModel.getRepaymentTime()));
                repayment.setCurrentPrincipal(new Double(repaymentBankModel.getPrincipal()));
                repayment.setCurrentTotalInterest(new Double(repaymentBankModel.getInterest()));
                repayment.setCurrentResidueAmount(new Double(repaymentBankModel.getRepaymentMonth()));
                if(repaymentBankModel.getDateStatus().equals("失败")){
                    repayment.setPayStatus(2);
                    repayment.setPayStatusNote("扣款失败");
                }else if(repaymentBankModel.getDateStatus().equals("成功")){
                    repayment.setPayStatus(1);
                    repayment.setPayStatusNote("扣款成功");
                }else {
                    repayment.setPayStatus(99);
                    repayment.setPayStatusNote("扣款异常");
                }
                logger.info("开始更新数据库表repayment中客户id为"+repayment.getCustomerId()+"的客户信息");
                int update=repaymentService.updatePayDateRepayment(repayment);
                //判断匹配条数
                if(update==0){
                    news.append("客户:"+repaymentBankModel.getName() + "身份证号为:"+ repaymentBankModel.getIdnumber()+"信息不存在,请核对!");
                    continue;
                }
                logger.info(update+"条更新了");
            }
            int update=repaymentService.updateStatus(date);
            logger.info(update+"条更新了");
            res=  news==null?null:news.toString();
            return res;
        }
    
    
        /**
         * Title: getMap
         * Description: bean中字段与Excel中位置的对应关系
         *
         * @author: xiqingning
         * @Date: 2019/07/12 18:50
         */
        public static Map<String, Integer> getMap() {
            Map<String, Integer> map = new HashMap<>();
            map.put("name", 0);
            map.put("idnumber", 1);
            map.put("repaymentTime", 2);
            map.put("principal", 3);
            map.put("interest", 4);
            map.put("repaymentMonth", 5);
            map.put("dateStatus", 6);
            map.put("remark", 7);
            return map;
        }
    
    
        /**
         * Title: downloadExcel
         * Description: 下载
         *
         * @author: xiqignning
         * @Date: 2019/7/15 17:35
         */
        @RequestMapping(value = "/file/fileBankDownLoad", method = RequestMethod.GET)
        public void fileBankDownLoad(HttpServletRequest request, HttpServletResponse response) {
            if (StringUtils.isEmpty(request.getParameter("id"))) {
                return;
            }
            String idStr = request.getParameter("id");
            UploadFileBank uploadFile = uploadFileBankService.selectByPrimaryKey(Integer.parseInt(idStr));
    
            String fileName = uploadFile.getFileName();
            //拼接文件路径
            String filePath = contractCodePath + "uploadFile/" + uploadFile.getFileUrl();
    
            try {
                DownLoadFileUtils.downloanExcelForXlsx(filePath,response,fileName);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    

      

    @RestController
    public class UploadFileBankController extends BaseController
    上边是文件controller

    配置文件读取的地址
    @Value("${contract.pathBank}")
    private String contractCodePath;

    实体类UpLoadFileBankData  用于接受前台参数  用于条件查询
    
    
    /**
     * @program: postloan
     * @description: 接受前台参数,用于条件查询
     * @author: 席清宁
     * @create: 2019-07-16 11:17
     **/
    package com.cfam.entity;
    
    import com.cfam.base.BaseModel;
    
    import java.util.Date;
    
    public class UpLoadFileBankData  extends BaseModel {
        private String productType;
        private String uploadState;
        private Date minTimes;
        private Date maxTimes;
    
        public String getProductType() {
            return productType;
        }
    
        public void setProductType(String productType) {
            this.productType = productType;
        }
    
        public String getUploadState() {
            return uploadState;
        }
    
        public void setUploadState(String uploadState) {
            this.uploadState = uploadState;
        }
    
        public Date getMinTimes() {
            return minTimes;
        }
    
        public void setMinTimes(Date minTimes) {
            this.minTimes = minTimes;
        }
    
        public Date getMaxTimes() {
            return maxTimes;
        }
    
        public void setMaxTimes(Date maxTimes) {
            this.maxTimes = maxTimes;
        }
    }

    前台页面效果

    工具类

     /**
         * <p>Title: uploadFileByPathAndName</p>
         * <p>Description: 上传文件</p>
         * @author xiaogang
         * @param file
         * @param filePath
         * @param fileName
         * @return
         */
        public static boolean uploadFileByPathAndName(MultipartFile file, String filePath, String fileName) {
    
             if (!file.isEmpty()) {
                try {//如果文件存在
                    File fileTempDir = new File(filePath);
                     if (!fileTempDir.exists()  && !fileTempDir.isDirectory()) {
                         fileTempDir.mkdirs();//先创建对应模块的文件夹
                    }
                    File fileTemp = new File(filePath + "/" + fileName);//建立对应的文件
                    System.out.println("生成文件地址 : "+filePath + "/" + fileName);
                    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fileTemp));
                    out.write(((MultipartFile) file).getBytes());//将文件内容写到具体地址的新建文件中
                    out.flush();
                    out.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    return false;
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
            } else {
                return false;
            }
            return true;
        }
    
        /**
         * <p>Title: mkNewFileName</p>
         * <p>Description: 重命名重复文件名称 </p>
         * @author xiaogang
         * @param fileName
         * @return newFileName
         */
    //    public String mkNewFileName(String fileName){
    //        String newFileName = "";
    //        String simpleName = "";
    //        String fileTypeReal = "";
    //        int fileTypeIndex = fileName.indexOf(".");
    //        if(fileTypeIndex>0){
    //            fileTypeReal = fileName.substring(fileTypeIndex+1, fileName.length());
    //        }
    //        if(fileName.length()>0){
    //            simpleName = fileName.substring(0, fileTypeIndex);
    //            if(")".equals(simpleName.substring(simpleName.length()-1,simpleName.length()-0))){
    //                if("(".equals(simpleName.substring(simpleName.length()-3,simpleName.length()-2))){
    //                    int a = Integer.parseInt(simpleName.substring(simpleName.length()-2,simpleName.length()-1));
    //                    a+=1;
    //                    simpleName = simpleName.substring(0,simpleName.length()-3) + a + ")";
    //                }
    //            }else{
    //                simpleName = simpleName+"(1)";
    //            }
    //        }else{
    //            simpleName = "fileNameisNull";
    //        }
    //        newFileName = simpleName+"."+fileTypeReal;
    //        return newFileName;
    //    }
    
        /**
         * <p>Title: GetFileType</p>
         * <p>Description: 获取文件后缀</p>
         * @author xiaogang
         * @param fileName
         * @return
         */
        public static String GetFileType(String fileName) {
            String fileTypeReal = "";
            int fileTypeIndex = fileName.indexOf(".");
            if (fileTypeIndex > 0) {
                fileTypeReal = fileName.substring(fileTypeIndex + 1, fileName.length());
            }
            return fileTypeReal;
        }
    
        /**
         * <p>Title: GetUUIDFileName</p>
         * <p>Description: 生成UUID文件名</p>
         * @author xiaogang
         * @param index 文件后缀
         * @return
         */
        public static String GetUUIDFileName(String index) {
            return FileUploadItems.getUUID() + "." + index;
        }
    View Code

    excele工具类

      1 public class ExcelUtils {
      2     /**
      3      * Title: ExcelUtils
      4      * Description: 判断上传的excel是xls还是xlsx结尾的。
      5      *
      6      * @author: likaichuan
      7      * @Date: 2018/1/11 15:59
      8      */
      9     public static Workbook isXlsOrXlsx(InputStream inputStream, String path)  throws FileNotFoundException, IOException {
     10         Workbook workbook = null;
     11         if (path.endsWith(".xls")) {
     12             workbook = new HSSFWorkbook(inputStream);
     13         } else if (path.endsWith(".xlsx")){
     14             workbook = new XSSFWorkbook(inputStream);
     15         }
     16         return workbook;
     17     }
     18 
     19     /**
     20      * <p>Title: readExcelByRow</p>
     21      * <p>Description: 读取Excel的行</p>
     22      *
     23      * @param filePath
     24      * @param readSheetNum
     25      * @param readStartRowNum
     26      * @param clazz
     27      * @param beanExcelMap
     28      * @return
     29      * @author likaichuan
     30      */
     31     public static <T> List<T> readExcelByRow(String filePath, int readSheetNum, int readStartRowNum, Class<T> clazz, Map<String, Integer> beanExcelMap)
     32             throws Exception {
     33         InputStream inputStream = null;
     34         try {
     35             inputStream = new FileInputStream(filePath);
     36             Workbook workbook =isXlsOrXlsx(inputStream, filePath);
     37 //            HSSFWorkbook hssfWorkbook = new HSSFWorkbook(inputStream);
     38             return listBeanFromExcel(workbook, readSheetNum, readStartRowNum, clazz, beanExcelMap);
     39         } catch (FileNotFoundException e) {
     40             // TODO Auto-generated catch block
     41             e.printStackTrace();
     42             return new ArrayList<>();
     43         } catch (IOException e) {
     44             // TODO Auto-generated catch block
     45             e.printStackTrace();
     46             return new ArrayList<>();
     47         } finally {
     48             try {
     49                 inputStream.close();
     50             } catch (IOException e) {
     51                 e.printStackTrace();
     52             }
     53         }
     54 
     55 
     56     }
     57 
     58     /**
     59      * <p>Title: judgeExcelModel</p>
     60      * <p>Description: 对比上传的文件与模板是否一致</p>
     61      *
     62      * @param path
     63      * @param templatePath
     64      * @param sheetNum
     65      * @param rowNum
     66      * @return
     67      * @author likaichuan
     68      */
     69     public static Boolean judgeExcelModel(String path, String templatePath, int sheetNum, int rowNum) {
     70         InputStream inputStream = null;
     71         InputStream inputStreamServer = null;
     72         try {
     73             inputStream = new FileInputStream(path);
     74             Workbook workbook = isXlsOrXlsx(inputStream, path);
     75             inputStreamServer = new FileInputStream(templatePath);
     76             Workbook workbookServer = isXlsOrXlsx(inputStreamServer, templatePath);
     77             List<String> modelList = getListFromExcel(workbook, path, sheetNum, rowNum);
     78             List<String> uploadModelList = getListFromExcel(workbookServer, templatePath, 0, rowNum);
     79             if (modelList.equals(uploadModelList)) {
     80                 return true;
     81             } else {
     82                 return false;
     83             }
     84         } catch (Exception e) {
     85             e.printStackTrace();
     86             return false;
     87         } finally {
     88             try {
     89                 inputStream.close();
     90                 inputStreamServer.close();
     91             } catch (IOException e) {
     92                 e.printStackTrace();
     93             }
     94         }
     95     }
     96 
     97     /**
     98      * <p>Title: getListFromExcel</p>
     99      * <p>Description: 获取Excel的表头</p>
    100      *
    101      * @param workbook
    102      * @param filePath
    103      * @param sheetNum
    104      * @param rowNum
    105      * @return
    106      * @author likaichuan
    107      */
    108     private static List<String> getListFromExcel(Workbook workbook, String filePath, int sheetNum, int rowNum) {
    109         Sheet sheet = workbook.getSheetAt(sheetNum);
    110         List<String> list = new ArrayList<>();
    111         Row row = sheet.getRow(rowNum);
    112         for (int i = 0; i < row.getLastCellNum(); i++) {
    113             list.add(getValue(row.getCell(i)));
    114         }
    115 
    116         return list;
    117     }
    118 
    119     /**
    120      * <p>Title: getBeanFromExcel</p>
    121      * <p>Description: 将Excel读取到list中</p>
    122      *
    123      * @param workbook
    124      * @param sheetNum
    125      * @param dataStartRowNum
    126      * @param clazz
    127      * @param beanExcelMap
    128      * @return
    129      * @author likaichuan
    130      */
    131     private static <T> List<T> listBeanFromExcel(Workbook workbook, int sheetNum, int dataStartRowNum, Class<T> clazz, Map<String, Integer> beanExcelMap) {
    132         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    133         DecimalFormat df = new DecimalFormat("0.####");
    134         Sheet sheet = workbook.getSheetAt(sheetNum);
    135         List<T> list = new ArrayList<>();
    136         for (int rowNum = dataStartRowNum; rowNum <= sheet.getLastRowNum(); rowNum++) {
    137             Row row = sheet.getRow(rowNum);
    138             Map<String, String> map = new HashMap<>();
    139             if (row != null) {
    140                 for (Map.Entry<String, Integer> entry : beanExcelMap.entrySet()) {
    141                     try {
    142                         String value = "";
    143                         if (row.getCell(entry.getValue()) != null && getValue(row.getCell(entry.getValue())).trim().length() != 0 && row.getCell(entry.getValue()).getCellType() == Cell.CELL_TYPE_NUMERIC) {
    144                             if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(row.getCell(entry.getValue()))) {
    145                                 value = sdf.format(row.getCell(entry.getValue()).getDateCellValue());
    146                             } else {
    147                                 value = df.format(row.getCell(entry.getValue()).getNumericCellValue());
    148                             }
    149                         } else {
    150                             value = getValue(row.getCell(entry.getValue()));
    151                         }
    152 //                            xssfRow.getCell(entry.getValue())!=null&&getValue(xssfRow.getCell(entry.getValue())).trim().length()!=0&&xssfRow.getCell(entry.getValue()).getCellType()==Cell.CELL_TYPE_NUMERIC?
    153 //                                    (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(xssfRow.getCell(entry.getValue())) ? sdf.format(xssfRow.getCell(entry.getValue()).getDateCellValue()):df.format(xssfRow.getCell(entry.getValue()).getNumericCellValue()))
    154 //                                    :getValue(xssfRow.getCell(entry.getValue()))
    155                         map.put(entry.getKey(), value);
    156                     } catch (Exception e) {
    157                         e.printStackTrace();
    158                     }
    159                 }
    160                 list.add(getBean(clazz, map));
    161             }
    162         }
    163 
    164         return list;
    165     }
    166 
    167     /**
    168      * <p>Title: getValue</p>
    169      * <p>Description: 根据不同类型读取Excel中cell的值</p>
    170      *
    171      * @param cell
    172      * @return
    173      * @author likaichuan
    174      */
    175     @SuppressWarnings("static-access")
    176     private static String getValue(Cell cell) {
    177         String res = "";
    178         if (cell == null) {
    179             return "";
    180         }
    181         if (cell.getCellType() == cell.CELL_TYPE_BOOLEAN) {
    182             res = String.valueOf(cell.getBooleanCellValue());
    183         } else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) {
    184             res = String.valueOf(cell.getNumericCellValue());
    185         } else if (cell.getCellType() == cell.CELL_TYPE_FORMULA) {
    186             res = String.valueOf(cell.getNumericCellValue());
    187         } else {
    188             try {
    189                 res = String.valueOf(cell.getStringCellValue());
    190             }catch (Exception e) {
    191                 System.out.print(cell);
    192                 e.printStackTrace();
    193             }
    194         }
    195         return res;
    196     }
    197 
    198     /**
    199      * <p>Title: getBean</p>
    200      * <p>Description: 将Excel的一行赋值给对应的bean</p>
    201      *
    202      * @param clazz
    203      * @param map
    204      * @return
    205      * @author likaichuan
    206      */
    207     private static <T> T getBean(Class<T> clazz, Map<String, String> map) {
    208         T obj = null;
    209         try {
    210             obj = clazz.newInstance();
    211             Field[] fields = clazz.getDeclaredFields();
    212             for (Field field : fields) {
    213                 field.setAccessible(true);
    214                 field.set(obj, map.get(field.getName()));
    215                 field.setAccessible(false);
    216             }
    217         } catch (Exception e) {
    218             e.printStackTrace();
    219         }
    220         return obj;
    221     }
    View Code

    模版

    public class RepaymentBankModel extends BaseModel {
        //姓名
        private String name;
    
        //身份证号
        private String idnumber;
        //还款时间
        private String repaymentTime;
        //当期剩余应还本金
        private String principal;
        //当期剩余应还利息
        private String interest;
        //当期剩余应还月供
        private String repaymentMonth;
        //还款状态
            private String dateStatus;
        //备注
        private String remark;

    前台代码

    <template>
      <section style="padding:20px">
        <el-row>
          <strong class="title">银行还款数据导入</strong>
        </el-row>
        <br />
        <!-- 检索操作区域 -->
        <el-card>
          <el-form :model="searcher">
            <el-row>
              <el-col :span="8">
                <el-form-item label="起始时间">
                  <el-date-picker v-model="searcher.minTimes" type="date" value-format="yyyy-MM-dd"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="终止时间">
                  <el-date-picker v-model="searcher.maxTimes" type="date" value-format="yyyy-MM-dd"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="所属产品">
                  <el-select v-model="searcher.productType" placeholder="所属产品">
                    <el-option
                      v-for="item in productList"
                      :key="item.id"
                      :value="item.id"
                      :label="item.name"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="上传状态">
                  <el-select v-model="searcher.uploadState" placeholder="上传状态">
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-button type="primary" v-on:click="search()" style="text-align: center">查询</el-button>
                <el-button type="primary" v-on:click="reset()" style="text-align: center">重置</el-button>
                <el-button type="primary" v-on:click="showDialog()" style="text-align: center">上传文件</el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
        <br />
        <!-- 表格数据部分 -->
        <el-card class="dataimport-table">
          <el-table :data="list" border>
            <el-table-column prop="dataNo" label="序号" align="center" type="index" width="120" fixed></el-table-column>
            <!-- <el-table-column label="文件名称" align="center" width="250" fixed>
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click="viewDetailInfo(scope.row.fileName)"
                >{{ scope.row.fileName }}</el-button>
              </template>
            </el-table-column>-->
            <el-table-column prop="fileName" label="文件名" align="center"></el-table-column>
            <el-table-column prop="projectName" label="所属产品" align="center" width="300"></el-table-column>
            <el-table-column prop="uploadState" label="上传状态" align="center" width="300"></el-table-column>
            <el-table-column prop="createTime" label="上传时间" align="center" width="300"></el-table-column>
            <el-table-column prop="remark" label="备注" align="center" width="300"></el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button size="small" type="primary" @click="download(scope.row.id)">下载</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
    
        <el-dialog title="提示" width="30%" :before-close="handleClose" :visible.sync="dialogVisible">
          <span>
            <el-form :model="dialog" :inline="true">
              <el-form-item label="还款时间">
                <el-date-picker v-model="dialog.minTimes" type="date" value-format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>
              <el-form-item label="所属产品">
                <el-select v-model="dialog.productType" filterable value-key="name" placeholder="所属产品">
                  <el-option
                    v-for="item in productList"
                    :key="item.id"
                    :value="item"
                    :label="item.name"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-upload
                  class="upload-demo"
                  ref="upload"
                  :data="fileData"
                  :action="fileUrlBank"
                  :on-success="handleAvatarScucess"
                  :before-upload="beforeAvatarUpload"
                  :multiple="true"
                  :auto-upload="true"
                >
                  <el-button @click="dialogVisible = false">取 消</el-button>
                  <el-button
                    slot="trigger"
                    size="medium"
                    type="primary"
                    @click="dialogVisible = false"
                  >文件上传</el-button>
    
                  <!-- <el-button type="primary" @click="dialogVisible = false">确 定</el-button> -->
                </el-upload>
              </el-form-item>
            </el-form>
          </span>
        </el-dialog>
        <!-- 分页部分 -->
        <el-pagination
          style="text-align:center;margin-top: 20px;"
          background
          layout="total, prev, pager, next"
          :page-size="10"
          @current-change="pageChange"
          :total="total"
        ></el-pagination>
      </section>
    </template>
    <script>
    // 需要调用到的后台api
    import { productList, getTableList, getLocalhost } from "../api/api";
    import url from "../api/url";
    import ElCol from "element-ui/packages/col/src/col";
    import deductions_dialog from "@/components/reusable_template/deductions_dialog";
    export default {
      components: {
        ElCol,
        "deductions-dialog": deductions_dialog
      },
      data() {
        return {
          options: [
            {
              value: "上传成功",
              label: "上传成功"
            },
            {
              value: "上传失败",
              label: "上传失败"
            },
            {
              value: "上传异常",
              label: "上传异常"
            }
          ],
          para: {
            minTimes: "",
            productType: "",
            name: ""
          },
          versionTemp: { id: null, name: null },
    
          dialogVisible: false,
          // 所属产品
          productList: [],
          fileData: {
            dataStr: ""
          },
          fileUrlBank: url.fileUrlBank,
          // 搜索输入框
          dialog: {
            customerName: "",
            minTimes:null,
            productType:null,
            // 固定代理商名称
            dealerName: this.$store.getters.dealerName,
            // isLate:"",
            // productType: {
            //   name: ""
            // },
            // minTimes:null,
            // maxTimes:null,
            page: 1,
            size: 12
          },
          searcher: {
            // 固定代理商名称
            //dealerName: this.$store.getters.dealerName,
            // isLate:"",
            productType: null,
            minTimes: null,
            maxTimes: null,
            uploadState:null
          },
          total: 0,
          queryButton: 1,
          list: [], //数据展示列表
          rules: this.$validate.rules,
          customer: {}
        };
      },
      methods: {
        download(id) {
          getLocalhost({}).then(data => {
            var localhost = data.data;
            console.log("==================");
            console.log(localhost);
            window.location.href = localhost + "/file/fileBankDownLoad?id=" + id;
          });
        },
    
    
    
        getTableList(type) {
          this.searcher={
            productType: type.productType,
            minTimes: type.minTimes,
            maxTimes: type.maxTimes,
            uploadState: type.uploadState
          }
          getTableList(this.searcher).then(data => {
            this.total = data.data.total;
            this.list = data.data.list;
          });
        },
        getlist() {
          this.getTableList(this.searcher);
        },
        handleClose(done) {
          this.$confirm("确认关闭?")
            .then(_ => {
              done();
            })
            .catch(_ => {});
        },
    
        //上传成功后
        handleAvatarScucess(res, file) {
          // if (this.searcher == "") {
          //   return;
          // }
          //清楚上传文件列表
          this.$refs.upload.clearFiles();
          if (res.code == 0) {
            //去查询已上传文件列表
            this.getTableList(this.searcher);
            this.$message(res.data);
          } else {
            //给出提示信息
            this.$notify.error({
              title: "上传失败",
              message: "上传失败",
              duration: 2500,
              offset: 100
            });
          }
        },
        //上传前对文件进行处理
        beforeAvatarUpload(file) {
          let _this = this;
          if (_this.dialog.minTimes == null || _this.dialog.productType == null) {
            this.$message.error("请选择还款时间与所属产品");
            return;
          }
          console.log(_this.dialog.minTimes);
          return new Promise((resolve, reject) => {
            //获取文件扩展名
            var fileExtension = file.name.substring(file.name.lastIndexOf(".") + 1);
            if (
              fileExtension == "xls" ||
              fileExtension == "xlsx" ||
              fileExtension == "csv"
            ) {
              //name id
              _this.para.productType = _this.dialog.productType.id;
              _this.para.minTimes = _this.dialog.minTimes;
              _this.para.name = _this.dialog.productType.name;
              console.log(_this.para);
              _this.fileData.dataStr = JSON.stringify(_this.para);
              resolve(file);
            } else {
              resolve(file);
              this.$message.error("上传文件错误");
              return;
            }
          });
        },
    
        //分页
        pageChange(val) {
          this.searcher.page = val;
          console.log("------------------------------------");
          console.log("queryButton:" + this.queryButton);
          if (this.queryButton == 1) {
            this.getTableList(this.searcher);
          } else {
            this.getTableList(this.searcher);
          }
        },
        //查詢
        search() {
          //let map = this.searcher;
          this.searcher.page = 1
          this.getTableList(this.searcher)
          //this.getTableList(map);
        },
        /**
         * 重置按钮
         */
        reset() {
          this.searcher = {
            //搜索输入框
            customerName: "",
            uploadState:null,
            //dealerName: this.$store.getters.dealerName,
            // isLate:"",
            minTimes: null,
            maxTimes: null,
            page: 1,
            size: 12
          };
        },
        getAllProducts() {
          this.productList = this.$store.getters.productList;
        },
        //文件上传
        showDialog() {
          this.dialogVisible = true;
        }
      },
    
      mounted() {
        this.getAllProducts();
        this.getTableList(this.searcher);
      }
    };
    </script>
    
    
  • 相关阅读:
    ASP.NET MVC5(二):控制器、视图与模型
    LINUX重启MYSQL的命令
    mysql unrecognized service问题解决
    UML类图几种关系的总结
    java用org.apache.poi包操作excel
    struts2.xml 中result type属性说明
    MySql Host is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts' 解决方法
    报错:1130-host ... is not allowed to connect to this MySql server 开放mysql远程连接 不使用localhost
    linux下使用yum安装mysql
    关于LINUX权限-bash: ./startup.sh: Permission denied
  • 原文地址:https://www.cnblogs.com/xining/p/11197229.html
Copyright © 2011-2022 走看看