ajax传输文件+检验

总共分为三个过程。

1、前端文件导入:

文件导入页面:

1 <input type="file" name="file" id="file1" style="width: 500px;" contentEditable="false" onchange="checkFile(this.value)"/>
 1 function checkFile(name){ 
 2          if(/^.+\.(txt)$/i.test(name.toLowerCase())){
 3          }else{
 4             alert("请上传格式为TXT的文件!");
 5             form1.reset();
 6          } 
 7       }  
 8     function submits() {
 9         var reSpaceCheck = /^\s*$/; // 判断空格
10         var uploadFileList = $('input[name^="attach"]');
11         for (var i=0; i< uploadFileList.length; i++){  
12             if (reSpaceCheck.test(uploadFileList[i].value)) {
13                 alert("上传文件不能为空!");
14                 return false;
15             }
16         }
17         if($("#file1").val()==null||$("#file1").val()==""){
18             alert("请上传文件!");
19             return false;
20         }
21         if(window.confirm("您确定导入文件中的数据吗?")){
22             setButtonState(false);
23             //ajax校验文件
24             ajaxCheckFile();
25         }
26     }
27     function setButtonState(enabled) {
28         $("button").prop("disabled", enabled);
29     }
30     
31     function ajaxCheckFile() {
32     $.ajaxFileUpload({
33         url:"<%=basePath%>remConfigure/importAssesmentInfo.action",
34         files:["file1"],
35         async:false,
36         dataType:"json",
37         success: function (data){
38             if(data!=null && ""!=data){
39                 data = $.parseJSON(data);
40                 if(data.success){
41                      setButtonState(true);
42                     alert("导入成功!");
43                 }else{
44                     setButtonState(true);
45                     asyncbox.success(data.message,"提示",function(){
46                         return true;
47                     });
48                 }
49             }
50         },
51         error: function (data,status,e){
52             setButtonState(false);
53             asyncbox.success("导入数据格式错误!","提示",function(){
54                 setButtonState(true);
55             });
56         }
57     });
58     return false;
59 }    
60 
61     function resetFile(){
62         var obj = document.getElementById('file1'); 
63         obj.outerHTML=obj.outerHTML; 
64     }

checkFile用来检验传入的文件必须为txt文件;

submits做一系列的检验后将文件传到后端;

setButtonState文件在后端的操作结束之前将按钮置灰直到后端返回true后;

ajaxCheckFile利用ajax传输文件;

resetFile重置文件。检验完成后跳转到action中。action中的文件通过setter方法注入。

 

2、后端处理。

 1     /**目标考核上传文件
 2      * ajax 校验 批量文件
 3      * @return 成功返回 {"success": true}
 4      * 失败返回 {"success": false, "message": 错误信息}
 5      */
 6     public String importAssesmentInfo(){
 7         HttpServletResponse response = ServletActionContext.getResponse();
 8         response.setContentType("text/html");
 9         response.setCharacterEncoding("UTF-8");
10         try {
11             if (file!= null) {
12                 readAndIptTxtFile(file);
13                 if (checkMessage.size() != 0) {
14                     StringBuilder sb = new StringBuilder();
15                     for (String s : checkMessage) {
16                         sb.append(s).append("<br/>");
17                     }
18                     errMsg = sb.toString();
19                     JSONObject jo = new JSONObject();
20                     jo.put("success", false);
21                     jo.put("message", errMsg);
22                     response.getWriter().write(jo.toString());
23                 } else {
24                     response.getWriter().write("{\"success\": true}");
25                 }
26             }
27         } catch (Exception e) {
28             e.printStackTrace();
29         }
30         return null;
31     }
readAndIptTxtFile(file)读取文件并且对该文件操作(逐行导入数据),checkMessage用来储存错误信息,如果有错误信息,则返回前端false和错误信息,如果没有则返回前端true。
 1 private void readAndIptTxtFile(File file) {
 2         BufferedReader bufferedReader = null;
 3         try {
 4             if (file.isFile() && file.exists()) { // 判断文件是否存在
 5                 bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
 6                 String line;
 7                 List<String> list=new ArrayList<String>();
 8 
 9                 //读取第一行数据
10                 line = bufferedReader.readLine();
11                 if (line == null) {
12                     //空文件
13                     throw new Exception("月目标考核导入文件是空文件");
14                 }
15 
16                 checkFirstLine(line);
17 
18                 //读取文件内容
19                 while ((line = bufferedReader.readLine()) != null) {
20                     list.add(line.trim());
21                 }
22                 if(list.isEmpty()) {
23                     checkMessage.add("月目标考核导入文件是空文件");
24                     return;
25                 }else{
26                     for(int i=0;i<list.size();i++){
27                         try{
28                             addData(list.get(i),i+1);
29                         }catch (Exception e) {
30                             arrResp.clear();
31                             checkMessage.add("文件格式错误,错误在第"+(i+1)+"行");
32                             break;
33                         }
34                     }
35                     if(arrResp.size()!=0)
36                         commonService.saveAll(arrResp);
37                     else
38                         errMsg = "文件格式错误";
39                 }
40             } else {
41                 checkMessage.add("找不到指定的文件");
42             }
43         } catch (Exception e) {
44             checkMessage.add(e.getMessage());
45         } finally {
46             if(bufferedReader != null) {
47                 try {
48                     bufferedReader.close();
49                 } catch (IOException e) {
50                     e.printStackTrace();
51                 }
52             }
53         }
54     }

因为业务要求需要检验第一行的字段格式,所以用checkFirstLine方法去检验第一行的格式然后导入剩下的行数据,addData方法用来将每行数据插入数据库,如果操作抛出异常则将存储插入对象的list清空,如果没有异常则执行插入的方法。

 1 /**
 2      * 检查第一行
 3      * @param line 第一行数据
 4      * @throws Exception 列名错误或第一列不为开始时间  时抛出异常
 5      */
 6     private void checkFirstLine(String line) throws Exception {
 7         line = line.trim();
 8         String[] firstLines = line.split("\\|", -1);
 9 
10         if ("开始时间".equals(firstLines[0])){ //自定义文件导入
11             titles = firstLines;
12             outter: for (String firstLine : firstLines) {
13                 for (String fullTitle : fullTitles) {
14                     if (fullTitle.equals(firstLine)) {
15                         continue outter;
16                     }
17                 }
18                 throw new Exception("列名称错误: " + firstLine);
19             }
20         } else {
21             throw new Exception("第一列必须为开始时间");
22         }
23     }
3、前端响应。
 1  success: function (data){
 2              if(data!=null && ""!=data){
 3                  data = $.parseJSON(data);
 4                  if(data.success){
 5                       setButtonState(true);
 6                      alert("导入成功!");
 7                  }else{
 8                      setButtonState(true);
 9                     asyncbox.success(data.message,"提示",function(){
10                          return true;
11                      });
12                  }
13              }
14          },

data:返回的数据。data.success=true则表示"前端传入文件—后端处理—返回处理信息给前端"这一过程完成。

 
posted on 2017-05-31 12:02 popcorn丫 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/popcornya/p/6923488.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值