基于原生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(); %>
上传者:
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); 这样基本的上传功能了。