Home > Web Front-end > JS Tutorial > body text

How to implement batch upload and download of files with Ajax

php中世界最好的语言
Release: 2018-03-30 16:59:45
Original
2914 people have browsed it

This time I will show you how to implement batch upload and download of files with Ajax. What are the precautions for implementing batch upload and download of files with Ajax? The following is a practical case, let's take a look.

I uploaded and downloaded files today. To summarize briefly, the basic web project establishment and SpringMVC framework construction will not be written in detail here.

Upload form:

<form id="uploadfiles" enctype="multipart/form-data">
    <input type="file" multiple="multiple" id="file_upload" name="file_upload" /> 
    <input type="button" value="上传" onclick="upload()" />
</form>
Copy after login

Upload Ajax:

<script type="text/javascript">
/*
 * 上传文件
 */
function upload(){
  var formData = new FormData($( "#uploadfiles" )[0]);
   $.ajax({
      type: "post",
      url: "./path/upload",
      dataType: "json",
      data: formData,
      /**  
       *必须false才会自动加上正确的Content-Type  
       */ 
      contentType : false, 
      /**  
       * 必须false才会避开jQuery对 formdata 的默认处理  
       * XMLHttpRequest会对 formdata 进行正确的处理  
       */ 
      processData : false,
      success: function(data){//从后端返回数据进行处理
       if(data){
         alert("上传成功!");
       }else{
         alert("上传失败!");
       }
      },
      error: function(err) {//提交出错
        $("#msg").html(JSON.stringify(err));//打出响应信息
        alert("服务器无响应");
       }
     });
}
</script>
Copy after login

spring.xml configuration plus:

<!-- 配置文件上传 -->
  <bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 默认编码 -->
    <property name="defaultEncoding" value="utf-8" />
    <!-- 文件大小最大值 -->
    <property name="maxUploadSize" value="10485760000" />
    <!-- 内存中的最大值 -->
    <property name="maxInMemorySize" value="40960" />
  </bean>
controller:
/*
   * 上传多个文件
   */
  @RequestMapping(value = "/upload", produces = "application/json;charset=UTF-8")
  public @ResponseBody
  boolean uploadFiles(@RequestParam("file_upload") MultipartFile [] files) {
    boolean result = false;
    String realPath;
    for(int i=0;i<files.length;i++){
      if (!files[i].isEmpty()) { 
          String uniqueName=files[i].getOriginalFilename();//得到文件名
          realPath="E:"+File.separator+uniqueName;//文件上传的路径这里为E盘
          files[i].transferTo(new File(realPath));  // 转存文件
          result = true;      
        } catch (Exception e) { 
          e.printStackTrace(); 
        } 
      }
    }
    return result;
  }
Copy after login

The downloaded jsp page code is designed by yourself according to different needs. Here is the controller code:

/*
   * 下载多个文件
   */
  @RequestMapping(value = "/download")
  public void downloadFiles(HttpServletResponse response) {
    String str= request.getParameter("rows");//下载文件信息,包括文件名、存储路径等
    JSONArray path=(JSONArray) JSONArray.parse(request.getParameter("rows"));
    Path paths[]=new Path[path.size()];
    paths = JSONArray.parseArray(str, Path.class).toArray(paths);
    String uri = "d:"+ File.separator + "mldn.zip";//临时文件存储路径
    File zipFile = new File(uri) ;  // 定义压缩文件名称 
    ZipOutputStream zipOut = null;// 声明压缩流对象 
    InputStream input = null;
    //将要压缩的文件加入到压缩输出流中
    try {
      zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    for(int i = 0;i<paths.length;i++){
      File file = new File(paths[i].getUri()+File.separator+paths[i].getFilename());
      try {
        input = new FileInputStream(file) ;// 定义文件的输入流 
        zipOut.putNextEntry(new ZipEntry(file.getName())) ; // 设置ZipEntry对象 
      } catch (Exception e) {
        e.printStackTrace();
      } 
    }
    //将文件写入到压缩文件中
    int temp = 0 ; 
    try {
      while((temp=input.read())!=-1){ // 读取内容 
        zipOut.write(temp) ;  // 写到压缩文件中 
      }
    } catch (IOException e) {
      e.printStackTrace();
    }finally{ 
      try {
        input.close() ;
        zipOut.close() ; 
      } catch (IOException e) {
        e.printStackTrace();
      } 
    }
    try {
      // 以流的形式下载文件。
      BufferedInputStream fis = new BufferedInputStream(new FileInputStream(zipFile));
      byte[] buffer = new byte[fis.available()];
      fis.read(buffer);
      fis.close();
      // 清空response
      response.reset();
      OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
      response.setContentType("application/x-msdownload;"); 
      response.setHeader("Content-Disposition", "attachment;filename=" + zipFile.getName());
      toClient.write(buffer);
      toClient.flush();
      toClient.close();
      zipFile.delete();    //将生成的服务器端文件删除
    } 
    catch (IOException ex) {
      ex.printStackTrace();
    }  
  }
Copy after login

Download multiple files into a compressed package, and then download the generated temporary compressed file delete.

If you use Ajax to submit a request on the download page, please note: the return types of the ajax function are only xml, text, json, html and other types, and there is no "stream" type, so we need to implement ajax download and cannot use the corresponding The ajax function performs

file download. But you can use js to generate a form, use this form to submit parameters, and return "stream" type data.

Example:

function download(){
    var form=$("<form>");//定义一个form表单
    form.attr("style","display:none");
    form.attr("target","");
    form.attr("method","post");
    form.attr("action","./path/download");//请求url
    var input1=$("<input>");
    input1.attr("type","hidden");
    input1.attr("name","rows");//设置属性的名字
    input1.attr("value",“test”);//设置属性的值
    $("body").append(form);//将表单放置在web中
    form.append(input1);
    form.submit();//表单提交       
              }
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Ajax+Servlet to implement non-refresh drop-down linkage (with code)

How to use Ajax asynchronously Check if the username is duplicate

The above is the detailed content of How to implement batch upload and download of files with Ajax. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template