原本打算使用jquery插件進(jìn)行異步文件上傳,比如uploadfy但是需要額外的支持,也有人用iframe模仿異步上傳機(jī)制,感覺都比較別扭。因?yàn)轫?xiàng)目不考慮低版本瀏覽器,所以決定用html5實(shí)現(xiàn)。下面只是一個(gè)簡(jiǎn)單的demo,具體樣式需要自己去做。
后臺(tái)基于strut2進(jìn)行文件處理,具體因項(xiàng)目而定。只是要注意設(shè)置文件大小的限制。 <constant name="struts.multipart.maxSize" value="52428800"/>這個(gè)配置根據(jù)具體情況設(shè)定,超過此值會(huì)報(bào)404.
首先是上傳頁面,比較簡(jiǎn)單,附帶了文件上者這個(gè)參數(shù)。
upload.jsp
<%@page language="java" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%> <% String path = request.getContextPath(); %> <!DOCTYPE html> <html> <head> <title>使用XMLHttpRequest上傳文件</title> <script type="text/javascript"> var xhr = new XMLHttpRequest(); //監(jiān)聽選擇文件信息 function fileSelected() { //HTML5文件API操作 var file = document.getElementById('fileName').files[0]; if (file) { var fileSize = 0; if (file.size > 1024 * 1024) fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB'; else fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB'; document.getElementById('fileName').innerHTML = 'Name: ' + file.name; document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize; document.getElementById('fileType').innerHTML = 'Type: ' + file.type; } } //上傳文件 function uploadFile() { var fd = new FormData(); //關(guān)聯(lián)表單數(shù)據(jù),可以是自定義參數(shù) fd.append("name", document.getElementById('name').value); fd.append("fileName", document.getElementById('fileName').files[0]); //監(jiān)聽事件 xhr.upload.addEventListener("progress", uploadProgress, false); xhr.addEventListener("load", uploadComplete, false); xhr.addEventListener("error", uploadFailed, false); xhr.addEventListener("abort", uploadCanceled, false); //發(fā)送文件和表單自定義參數(shù) xhr.open("POST", "<%=path%>/user/uploadifyTest_doUpload"); xhr.send(fd); } //取消上傳 function cancleUploadFile(){ xhr.abort(); } //上傳進(jìn)度 function uploadProgress(evt) { if (evt.lengthComputable) { var percentComplete = Math.round(evt.loaded * 100 / evt.total); document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%'; } else { document.getElementById('progressNumber').innerHTML = 'unable to compute'; } } //上傳成功響應(yīng) function uploadComplete(evt) { //服務(wù)斷接收完文件返回的結(jié)果 alert(evt.target.responseText); } //上傳失敗 function uploadFailed(evt) { alert("上傳失敗"); } //取消上傳 function uploadCanceled(evt) { alert("您取消了本次上傳."); } </script> </head> <body> <form id="form1" enctype="multipart/form-data" method="post" action="upload.php"> <div class="row"> <label for="fileToUpload">選擇文件</label> <input type="file" name="fileName" id="fileName" onchange="fileSelected();"/> </div> <div id="fileName"></div> <div id="fileSize"></div> <div id="fileType"></div> <div class="row"> 上傳者:<input type="text" name="name" id="name"/> <input type="button" onclick="uploadFile()" value="上傳" /> <input type="button" onclick="cancleUploadFile()" value="取消" /> </div> <div id="progressNumber"></div> </form> </body> </html>
fd.append("name", document.getElementById('name').value);
fd.append("fileName", document.getElementById('fileName').files[0]);
這兩句是把數(shù)據(jù)綁定到表單。因?yàn)閔tml5支持多文件上傳,所以
document.getElementById('fileName').files
返回的是數(shù)組。這里只有一個(gè)文件所以取下標(biāo)0的元素。
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
這里綁定進(jìn)度、上傳、錯(cuò)誤、中斷的事件,提供一些交互。文件進(jìn)度顯示就是在progress回調(diào)中進(jìn)行顯示的。
然后貼上后臺(tái)代碼和action配置,UploadifyTestAction.java
package com.bjhit.eranges.actions.test; import java.io.File; import com.opensymphony.xwork2.ActionSupport; public class UploadifyTestAction extends ActionSupport { private static final long serialVersionUID = 837481714629791752L; private File fileName; private String name; private String responseInfo; public String doUpload() throws Exception { System.out.println(name); File myFile = fileName; System.out.println(myFile.getName()); responseInfo = "上傳成功!"; return "doUpload"; } public String getName() { return name; } public void setName(String name) { this.name = name; } public File getFileName() { return fileName; } public void setFileName(File fileName) { this.fileName = fileName; } public String getResponseInfo() { return responseInfo; } public void setResponseInfo(String responseInfo) { this.responseInfo = responseInfo; } }
action配置
<!-- 文件上傳例子 --> <action name="uploadifyTest_*" class="com.bjhit.eranges.actions.test.UploadifyTestAction" method="{1}"> <result name="doUpload" type="json"> <param name="includeProperties">responseInfo</param> <param name="excludeNullProperties">true</param> </result> </action>
這樣基本的上傳功能就實(shí)現(xiàn)了。
感謝大家的閱讀,希望本文所述對(duì)大家學(xué)習(xí)Ajax方式文件上傳進(jìn)度條實(shí)現(xiàn)方法有所幫助。
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com