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

所属分类: 网络编程 / AJAX相关 阅读数: 1060
收藏 0 赞 0 分享

今天做了文件的上传下载,小小总结一下,基本的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实现文件批量上传和下载功能实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

更多精彩内容其他人还在看

ajax中文乱码问题解决方案

ajax中文乱码问题在中文中经常会出现这种问题,其实只要稍加注意就不会出现ajax中文乱码这回事情了,接下来为大家详细介绍下如何解决这类问题
收藏 0 赞 0 分享

jquery ajax实现批量删除具体思路及代码

回调函数,在请求完成后需要进行的操作:此处是把选中的checkbox去掉,接下来为大家详细介绍下,感兴趣的朋友可以参考下哈,希望对你有所帮助
收藏 0 赞 0 分享

JQuery+ajax实现批量上传图片(自写)

jquery+ajax方式实现单张图片上传的代码是可以搜的到,实现批量上传图片的程序却没搜索到于是自己写了个,感兴趣的朋友可以参考下
收藏 0 赞 0 分享

利用Ajax实现在脚本里传值实例介绍

Ajax实现在脚本里传值可以解决实际上的一些问题,本文实现了一下,感兴趣的朋友可以参考下,希望可以帮助到你
收藏 0 赞 0 分享

jQuery+Ajax实现表格数据不同列标题排序(为表格注入活力)

CSS也使得表格的布局越来越光彩耀人。但是,无论如何,都掩饰不了那些包装下的死板,接下来为大家介绍下让那些死板的数据 更具有可读性、可用性
收藏 0 赞 0 分享

jQery ajax——load()方法示例介绍

load(url,[data],[callback])url:加载的页面地址;data: 可选项,发送到服务器的数据,格式是key/value;callback:可选项,回调函数,示例代码如下
收藏 0 赞 0 分享

滑轮滚动到页面底部ajax加载数据配合jsonp实现探讨

滚动下拉到页面底部加载数据是很多瀑布流网站的做法,那来看看配合jsonp是如何实现的吧,小菜总结记录之用特在此与大家一起分享,感兴趣的朋友可以参考下哈
收藏 0 赞 0 分享

ajax 登录功能简单实现(未连接数据库)

未连接数据库下实现ajax 登录功能判断登陆成功与失败,喜欢ajax的朋友可以参考下哈,希望对大家有所帮助
收藏 0 赞 0 分享

AJAX和WebService实现邮箱验证(无刷新验证邮件地址是否合法)

首先在项目里面添加服务引用,验证 Email 地址是否正确(邮件地址合法、只是域名正确、邮件服务器没有找到等等)感兴趣的朋友可以参考下哈
收藏 0 赞 0 分享

AJAX和三层架构实现分页功能具体思路及代码

本文涉及到AJAX和三层架构方面的知识,在学习分页的同时也巩固了一下它们的相关知识,适合初学者的你
收藏 0 赞 0 分享
查看更多