Ajax利用FormData提交表單
一、ajax提交純表單(不包含檔案或二進位制或非ASCII資料)
ajax提交表單繞了很久,遇到一些問題進行測試下以加深理解,測試使用瀏覽器 49.0.2623.110 m,HTML使用HTML4標準。下文提到的ajax為原生javascript的ajax(指令碼化HTTP),都是個人理解,如有錯誤還望被指正。關於AJAX,XMLHttpRequest,FormData等應該還有許多待深入的問題,還需要進一步學習,本文僅目前實踐內容。
二、ajax上傳檔案
1、 上傳單個檔案
/* ajaxupload.jsp */
<%@ page contentType="text/html; charset = utf-8
<!DOCTYPE html>
<html>
<head>
<title>Asynchronous Javascript and XML</title>
</head>
<body>
請選擇要上傳的檔案:<input id="uploadItem"name="uploadItem" type="file">
<script>
var test= function x(){
var elem= document.
elem.addEventListener("change",function() {
var item= document.getElementById("uploadItem").files[0];
var formData = new FormData();
formData.append("uploadItem",item);
var xhr = new XMLHttpRequest();
//xhr.setRequestHeader("Content-Type","multipart/form-data");
xhr.send(formData);
},false);
}();
</script>
</body>
</html>
/*upload */
public class upload extends HttpServlet{
public void doPost(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException {
try {
request.setCharacterEncoding("UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
String fileName="";
File savefile ;
String apkPath = "D:/temp/";
for (FileItem item : items) {
if (!item.isFormField()) {
fileName = apkPath + item.getName();
System.out.println("fileName = " + fileName);
savefile = new File(fileName);
item.write(savefile);
}
}
}catch(Exception e){
e.printStackTrace();
}
PrintWriter out = null;
try {
out = response.getWriter();
}catch (Exception e){
e.printStackTrace();
}
out.println("upload successed!");
}
}
如下程式碼,定義一個type=file的input元件,監聽變化後直接上傳。
本人錯誤使用:設定了XMLHttpRequest的Content-Type為mutipart/form-data,這樣導致錯誤“the request was rejected because no multipartboundary was found”,下面是瀏覽器中HTTP請求頭資訊,我們可以看到Content-Type中沒有boundary(瀏覽器隨機生成)。
下面是成功傳送時候的HTTP請求資訊。
本人使用過的檔案上傳外掛Dropzone也是用FormData上傳檔案的,設定的請求頭屬性有Accecpt,Cache-Control,X-Requested-With,不包含Content-Type。從請求頭中我們可以看到Content-Type是自動被設定為multipart/form-data的。從HTTP請求資訊中我們還可以看到Request Payload,這是請求的有效荷載,也是一個值得討論的問題,可以跟請求引數的Query String Parameter做下比較。
2、 提交表單,表單中攜帶檔案
根據FormData的使用我們可以看到,將簡單的鍵值對資料和檔案資料放到FormData傳送是很簡單的一個問題,那麼問題在哪裡呢?問題在於後臺如何取到普通的表單資料。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html> <head> <title>提交包含資料和檔案的表單</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <script type="text/javascript"> function sendForm(){ var oData = new FormData(document.forms.namedItem("fileinfo")); oData.append("CustomField","This is some extra data"); var oReq = new XMLHttpRequest(); oReq.open("post","../upload",true); oReq.send(oData); } </script> </head> <body> <form enctype="multipart/form-data" method="post" name="fileinfo"> <table> <tr> <td><label>Your email address:</label></td> <td><input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64"/> </td> </tr> <tr> <td><label>Custom file label:</label></td> <td><input type="text" name="filelabel" size="12" maxlength="32"/><br/> </td> </tr> <tr> <td><label>File to stash:</label></td> <td><input type="file" name="file" required/> </td> </tr> </table> </form> <div id="output"></div> <a href="javascript:sendForm()">Stash the file!</a> </body> </html>
所有的資料都放在RequestPayload(原生AJAX使用)中,該如何轉換呢?Request.getParameter應該只能得到get請求中Query String Parameters或者post請求Form Data請求體中的資料。http://blog.csdn.net/mhmyqn/article/details/25561535?utm_source=tuicool&utm_medium=referral這個部落格講了用最原始的輸入流方法讀取Request Payload中的資料,但是這要設定Content-Type 為application/x-www-form-urlencoded。最後,轉了半天發現上傳元件的parseRequest轉化出來FileItem是包括fieldItem的(一開始以為只是file檔案的資訊被解析出來了),如果是表單域,java可以如下程式碼進行解析(參考網址http://www.blogjava.net/xyzroundo/articles/186217.html)
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { try { request.setCharacterEncoding("UTF-8"); boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = upload.parseRequest(request); //Process the uploaded items Iterator iter = items.iterator(); while(iter.hasNext()){ FileItem item = (FileItem)iter.next(); if(item.isFormField()){ String name =item.getFieldName(); String value = item.getString("UTF-8"); System.out.println("name = " + name + " ; value = " + value); } } } } catch (Exception e) { e.printStackTrace(); } PrintWriter out = null; try { out = response.getWriter(); } catch (Exception e) { e.printStackTrace(); } out.println("upload successed!"); }
3、 新增進度條
新增進度條HTML元素,並設定樣式,為XMLHttpRequest新增onprogress事件,涉及e.lengthComputable,e.uploaded,e.total的使用。
/*進度條元素*/
<tr class="progress-display"> <td>上傳進度:</td> <td><span id="progress-bar" class="progress-bar"><span class="progress-bar-after"></span></span></td> </tr>
/*進度條樣式*/
.progress-bar{ display:inline-block; background-color:honeydew; width:100px; height:10px; position:relative; border-radius: 2px; border:0.5px solid gray; } .progress-bar-after{ content:""; width:0%; height:10px; background-color:green; position:absolute; left:0; }
/*XMLHttpRequest新增onprogress事件*/
oReq.onprogress = function(e){ if(e.lengthComputable){ document.querySelector(".progress-bar-after").style.width = Math.round(100* e.loaded/ e.total) + "%"; } }
三、總結
做完上述工作以後發現AJAX通過FormData上傳檔案是件挺簡單的事情,不過應該考慮FormData的相容性。