当前位置: 移动技术网 > IT编程>脚本编程>Ajax > SpringMVC+Ajax实现文件批量上传和下载功能实例代码

SpringMVC+Ajax实现文件批量上传和下载功能实例代码

2017年12月07日  | 移动技术网IT编程  | 我要评论

今天做了文件的上传下载,小小总结一下,基本的web项目建立及springmvc框架搭建此处不详细写出来了。

上传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>

上传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>

spring.xml配置加上:

<!-- 配置文件上传 -->
  <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;
  }

下载的jsp页面代码根据需求不同自己设计,这里给出controller代码:

/*
   * 下载多个文件
   */
  @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();
    }  
  }

将多个文件打成一个压缩包下载,然后将生成的临时压缩文件删除。

下载页面如果用ajax提交请求的话要注意:ajax函数的返回类型只有xml、text、json、html等类型,没有“流”类型,所以我们要实现ajax下载,不能够使用相应的ajax函数进行文件下载。但可以用js生成一个form,用这个form提交参数,并返回“流”类型的数据。

例子:

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();//表单提交       
              }

总结

以上所述是小编给大家介绍的springmvc+ajax实现文件批量上传和下载功能实例代码,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网