使用ajax、servlet實現多檔案的上傳

來源:互聯網
上載者:User
搭建環境

這裡使用maven匯入jar包:

<dependencies>  <!--檔案上傳-->  <dependency>      <groupId>commons-fileupload</groupId>      <artifactId>commons-fileupload</artifactId>      <version>1.3.2</version>  </dependency>  <dependency>      <groupId>org.apache.commons</groupId>      <artifactId>commons-io</artifactId>      <version>1.3.2</version>  </dependency>  <!--json-->  <dependency>      <groupId>org.json</groupId>      <artifactId>json</artifactId>      <version>20160810</version>  </dependency></dependencies>



三個主要的jar包,這裡還將使用jquery以及非同步提交表單,所以需要jquery和jquery.form檔案
jsp頁面

<%--  Created by IntelliJ IDEA.  User: wqh  Date: 2017/5/26  Time: 9:46  To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"><script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.1.1.min.js"></script><script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.form.js"></script><script type="text/javascript">    $(function () {      $("#sub").bind("click",function () {          var option = {              type:"post",              url:"${pageContext.request.contextPath}/TestServlet",              async: true,              enctype:"multipart/form-data",              dataType:"json",              error:function(data){                  alert(data);              },              success:function(msg){                  //將結果格式化為json                  var json = eval(msg);                  var data = "";                  $.each(json,function (index,item) {                       var key = json[index].file;                       data = data +"==="+ key                  });                    alert(data);              }          };         $("#fileForm").ajaxSubmit(option);      })    });</script><head>    <title>Title</title></head><body>    <form action="#" id="fileForm" enctype="multipart/form-data" method="post" >        <input type="file" name="file"/><br>        <input type="file" name="file"/><br>        <input type="file" name="file"/><br>        <button type="submit"  name="sub" id="sub">提交</button>    </form></body></html>

servlet代碼

檔案上傳測試,上傳檔案就不儲存到本地l。直接向頁面返迴文件名,返回json格式。

 req.setCharacterEncoding("utf-8");        resp.setCharacterEncoding("utf-8");        List<String> fileName = new ArrayList<>();        boolean ismultipartContent = ServletFileUpload.isMultipartContent(req);        //判斷是否是檔案上傳        if (ismultipartContent) {            DiskFileItemFactory factory = new DiskFileItemFactory();            ServletFileUpload fileUpload = new ServletFileUpload(factory);            try {                List<FileItem> fileItems = fileUpload.parseRequest(req);                for (FileItem fileItem : fileItems) {                    //判斷欄位的類型                    if (fileItem.isFormField()) {                        //處理普通欄位                    } else{                        //檔案欄位,處理上傳欄位,這裡就不把檔案儲存到本地了                        fileName.add(fileItem.getName());                    }                }            } catch (FileUploadException e) {                e.printStackTrace();            }            //將list轉化為json            int index = 1;            JSONArray jsonArray = new JSONArray();            for (String s : fileName){                JSONObject jsonObject = new JSONObject();                jsonObject.put("file",s);                jsonArray.put(jsonObject);            }            resp.getWriter().print(jsonArray);        }
測試

選擇上傳的檔案


檔案上傳測試和返回json格式的檔案名稱成功。。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.