HTML5结合ajax实现文件上传以及进度显示
生活随笔
收集整理的這篇文章主要介紹了
HTML5结合ajax实现文件上传以及进度显示
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
基于原生html5實現,不需要falsh支持,進度可以自定義顯示,控制靈活,?本來打算使用jquery插件進行異步文件上傳,比如uploadfy但是需要額外的支持,也有人用iframe模仿異步上傳機制,感覺都比較別扭。因為項目不考慮低版本瀏覽器,所以決定用html5實現。下面只是一個簡單的demo,具體樣式需要自己去做。 后臺基于strut2進行文件處理,具體因項目而定。只是要注意設置文件大小的限制。? 這個配置根據具體情況設定,超過此值會報404. 首先是上傳頁面,比較簡單,附帶了文件上者這個參數。 upload.jsp <%@page language=“java” pageEncoding=“UTF-8” contentType=“text/html; charset=UTF-8”%> <% String path = request.getContextPath();? %> ??? 使用XMLHttpRequest上傳文件 ???
選擇文件 ??? 上傳者: ??? fd.append(“name”, document.getElementById(‘name’).value); fd.append(“fileName”, document.getElementById(‘fileName’).files[0]); 這兩句是把數據綁定到表單。因為html5支持多文件上傳,所以 document.getElementById(‘fileName’).files返回的是數組。這里只有一個文件所以取下標0的元素。 xhr.upload.addEventListener(“progress”, uploadProgress, false); ?xhr.addEventListener(“load”, uploadComplete, false); ?xhr.addEventListener(“error”, uploadFailed, false); ?xhr.addEventListener(“abort”, uploadCanceled, false);這里綁定進度、上傳、錯誤、中斷的事件,提供一些交互。文件進度顯示就是在progress回調中進行顯示的。 然后貼上后臺代碼和action配置,UploadifyTestAction.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 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配置 1 2 3 private?ImageView?image;???? image?=?(ImageView)?findViewById(R.id.xx_id);???? image.setAlpha(0);?這樣基本的上傳功能了。總結
以上是生活随笔為你收集整理的HTML5结合ajax实现文件上传以及进度显示的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何存储和恢复 HTML5 Canvas
- 下一篇: HTML5教程之-文件拖拽功能实现