Home  >  Article  >  Web Front-end  >  Introduction to the use of ajaxFileUpload asynchronous file upload

Introduction to the use of ajaxFileUpload asynchronous file upload

不言
不言Original
2018-07-02 16:55:121421browse

This article mainly introduces the simple use of ajaxFileUpload to upload files asynchronously. The jQuery plug-in AjaxFileUpload can realize ajax file upload. If you are interested, you can learn more.

Here is a brief introduction to ajaxFileUpload. The jQuery plug-in AjaxFileUpload can realize ajax file upload. Our project uses an architecture that separates jsp and js, so the code is as follows.

First is the jsp part:

<!-- <form method="post"> --> 
    <input type="file" name="n_file" id="fileToUpload" value="上传表格" /> 
     <button id="upload1" class="btn btn-default">上传</button> 
<!-- </form> -->

Here is why I commented out the form, because there is already another form in my jsp During the debugging process, I found that there might be a conflict and commented out the form. It turns out that ajaxFileUpload can be submitted without a form. Here is the js code part:

$(function(){  
  //点击打开文件选择器  
  $("#upload1").on(&#39;click&#39;, function() {  
    //选择文件之后执行上传  
 
    $.ajaxFileUpload({  
      url:&#39;supplyDataReportUploadExcel&#39;, //url自己写  
      secureuri:false, //这个是啥没啥用 
      type:&#39;post&#39;, 
      fileElementId:&#39;fileToUpload&#39;,//file标签的id  
      dataType: &#39;json&#39;,//返回数据的类型  
      //data:{name:&#39;logan&#39;},//一同上传的数据  
      success: function (data, status) {  
//       alert(data); 
//       alert(data.msg);   
//       alert(data.success); 
        if(data.success){ 
          alert("upload,success!!!"); 
          window.location.href=&#39;supplyDataReport&#39;; 
        }else{ 
          alert(data.msg); 
          window.location.href=&#39;supplyDataReport&#39;; 
        } 
         
      }/*,  
      error: function (data, status, e) {  
        alert(e);  
      }*/  
    });  
 
  });  
 
});

Myself js is not good, I just know how to use this js and cannot completely copy it. It needs to be combined with the actual situation of the project structure, but the comments on what the general parameters are used for are written. Be sure to note that the type of post is consistent with the method=RequestMethod.POST of the Controller method corresponding to the request. Note dataType:'json', be sure to pay attention to the case of json.

ps: Here I want to say that the judgment I use data.success is related to the subsequent entity class AjaxJson. Pay attention! ! ! ! !

By the way, the corresponding js needs to be introduced into the jsp as follows:

<script type="text/javascript">Core.js(&#39;./js/iface/upload&#39;);</script> 
<script type="text/javascript" src="libs/jquery/ajaxfileupload.js"></script>

The upload introduced in the first paragraph is the above js Content, our imported js has been encapsulated, so just write it directly. Based on the actual situation, the following js file of the jQuery plug-in AjaxFileUpload will be used.

The next step is how to respond to the Controller method:

@SuppressWarnings("resource") 
@RequestMapping(value = "/supplyDataReportUploadExcel", method = RequestMethod.POST) 
public @ResponseBody String supplyDataReportUploadExcel(HttpServletRequest request, HttpServletResponse response,MultipartFile n_file) throws Exception { 
  AjaxJson json = new AjaxJson(); 
  ObjectMapper mapper = new ObjectMapper(); 
  UploadFormBackVo uploadFormBackVo = new UploadFormBackVo(); 
  //判断是否是空的Excel 包括没有标题 
  if(n_file.getSize()>0){ 
    try{ 
      //先判断 文件名 是否符合规格 因为不知道怎么获取上传文件的路径 后期修改 
      //获取文件 
      //验证文件名 
      String fileName = n_file.getOriginalFilename(); 
      String fileNewName = fileName.replaceAll(".xls", ""); 
      String eL = "[a-zA-Z]+[0-9]{4}-[0-9]{2}-[0-9]{2}"; 
      Pattern p = Pattern.compile(eL); 
      Matcher m = p.matcher(fileNewName); 
      boolean dateFlag = m.matches(); 
      if (!dateFlag) { 
        System.out.println("格式错误"); 
        uploadFormBackVo.setFormName(n_file.getOriginalFilename()); 
        uploadFormBackVo.setUploadTime(new Date()); 
        uploadFormBackVo.setIfsuccess("上传失败,Excel文件名不符合规格!!!"); 
        supplyDataReportService.insert(uploadFormBackVo); 
         
        json.setSuccess(false); 
        json.setMsg("Excel,NameError!!!"); 
        String jsonStr = mapper.writeValueAsString(json); 
        return jsonStr; 
      } 
      //上传文件 
      UploadUtil.SaveFileFromInputStream(n_file.getInputStream(), "D:/补数据报表文件", n_file.getOriginalFilename()); 
      InputStream is2 = new FileInputStream("D:/补数据报表文件/"+n_file.getOriginalFilename()); 
       
      //读取文件进行内容验证 
      ExcelReader excelReader = new ExcelReader(); 
       
      Map<Integer, SupplyDataReportBackVo> supplyDataReportBackVos = new HashMap<Integer, SupplyDataReportBackVo>(); 
       
       
      String jsonStr = excelReader.readExcelContent(is2,supplyDataReportBackVos,json,n_file); 
      //判断 readExcelContent()解析Excel文件 是否符合规范 如果符合 修改相应数据  
      if(json.isSuccess()==true){ 
         //遍历map 用value --》SupplyDataReportBackVo 调用  updateById方法 
        for(SupplyDataReportBackVo supplyDataReportBackVo : supplyDataReportBackVos.values()){ 
          supplyDataReportService.updateById(supplyDataReportBackVo); 
        } 
         
        System.out.println("获得Excel表格的内容:"); 
        for (int i = 1; i <= supplyDataReportBackVos.size(); i++) { 
           
          System.out.println(supplyDataReportBackVos.get(i)); 
        } 
        //保存上传记录 
        uploadFormBackVo.setFormName(n_file.getOriginalFilename()); 
        uploadFormBackVo.setUploadTime(new Date()); 
        uploadFormBackVo.setIfsuccess("上传成功"); 
        supplyDataReportService.insert(uploadFormBackVo); 
        return jsonStr; 
      } 
      // 解析Excel 文件 中  有空值 保存这次上传的记录且删除已上传的Excel文件, 删除已上传的Excel文件已在 readExcelContent()中处理 
      uploadFormBackVo.setFormName(n_file.getOriginalFilename()); 
      uploadFormBackVo.setUploadTime(new Date()); 
      uploadFormBackVo.setIfsuccess("上传失败,Excel中有空值!!!"); 
      supplyDataReportService.insert(uploadFormBackVo); 
      return jsonStr; 
    } catch (IOException e){ 
      System.out.println(e.getMessage()); 
    } 
  }else{ 
    //ajax返回的数据 
    json.setSuccess(false); 
    json.setMsg("Upload File Null!!!!!"); 
    String jsonStr = mapper.writeValueAsString(json); 
    return jsonStr; 
  } 
  System.out.println("ajax请求成功"); 
  return ""; 
   
/    json.setMsg("upload,success!!!"); 
   
}

This method only needs to pay attention to a few points, and the rest is the author himself. For its own business logic, the first request method in @RequestMapping is POST, and the second parameter passed in is MultipartFile n_file. This n_file should correspond to the name attribute in the d5fd7aea971a85678ba271703566ebfd tag in jsp. The third thing to pay attention to is the annotation @ResponseBody on the return value Sting. The remaining two things to pay attention to are AjaxJson and ObjectMapper.

AjaxJson is a model class encapsulated by itself, used to handle ajax. As for ObjectMapper, it is used to convert types. Please use Baidu or brainstorming. The author is also limited to knowing how to use it. Paste AjaxJson below:

package com.zhongxin.web.ops.adrule.model; 
 
import java.util.Map; 
 
public class AjaxJson { 
   
  private boolean success = true; 
   
  private String msg = "ok"; 
   
  private Object obj = null; 
   
  private Map<String, Object> attributes; 
   
  public boolean isSuccess() { 
    return success; 
  } 
  public void setSuccess(boolean success) { 
    this.success = success; 
  } 
  public String getMsg() { 
    return msg; 
  } 
  public void setMsg(String msg) { 
    this.msg = msg; 
  } 
  public Object getObj() { 
    return obj; 
  } 
  public void setObj(Object obj) { 
    this.obj = obj; 
  } 
  public Map<String, Object> getAttributes() { 
    return attributes; 
  } 
  public void setAttributes(Map<String, Object> attributes) { 
    this.attributes = attributes; 
  } 
   
}

The above is the entire content of this article. I hope it will be helpful to everyone's learning. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

How to load navigation history when using jQuery mobile class library

Jquery ajax technology implements interval N Pass value to a page in seconds

The above is the detailed content of Introduction to the use of ajaxFileUpload asynchronous file upload. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn