使用JQuery的ajaxfileupload上传文件:
js:
function ajaxFileUpload(fileName){ if(!btnEnabler){ alert("文件上传中,请稍候..."); return; } btnEnabler = false; //load the loading image $("#fileLoading") .ajaxStart(function(){ $(this).show(); }) .ajaxComplete(function(){ $(this).hide(); }); //file upload $.ajaxFileUpload({ url:'<%=path%>/email/uploadAttach.action?fileName='+escape(escape(fileName)), secureuri:false, fileElementId:'oFile', dataType: 'json', success: function (data, status){ allFilePath=allFilePath + data.msg + "<*>"; showFile(); //clear the file selection dialog box var obj = document.getElementById("oFile"); obj.outerHTML=obj.outerHTML; btnEnabler = true; }, error: function (data, status, e){ alert("文件上传失败"); //clear the file selection dialog box var obj = document.getElementById("oFile"); obj.outerHTML=obj.outerHTML; btnEnabler = true; } }) }
页面部分:
<input type="file" id="oFile" name="oFile" οnchange="ajaxFileUpload(this.value);">
<font id="fileLoading" style="display:none"><img src="<%=path%>/resource/image/Emailimage/loading.gif" border="0" align="absmiddle"> 正在上传附件...</font>
后台action:
private static final SimpleDateFormat fileNameSdf=new SimpleDateFormat("yyyyMMddHHmmss");
private File oFile;
提供oFile的get/set方法;
public void uploadAttach() throws EmailException {
System.out.println("uploadAttach() invoke..." );
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
String uploadPath = EmailUtil.getUploadPath();
String fileNamePrefix = fileNameSdf.format(new Date());
String uploadFileName = Escape.unescape(request.getParameter("fileName"));
String storeFileName = uploadPath + fileNamePrefix + uploadFileName;
File storeFile = new File(storeFileName);
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(storeFile));
bis = new BufferedInputStream(new FileInputStream(oFile));
int c;
while ((c = bis.read()) != -1) {
bos.write(c);
bos.flush();
}
response.setContentType("text/html;charset=utf-8");
response.getWriter().write("{msg:'"+fileNamePrefix + uploadFileName+"'}");
} catch (IOException e) {
e.printStackTrace();
throw new EmailException("上传邮件附件出错!");
} finally {
try { bos.close(); } catch (IOException e) {e.printStackTrace();}
try { bis.close(); } catch (IOException e) {e.printStackTrace();}
}
}
困惑了半天的问题就是上传小于2M的文件没问题,但是上传大于2M的文件ajax返回error,action没有执行,找了半天是Struts2的default.properties配置文件对上传文件的限制为2M,要修改这个限制可以再struts.xml中修改这一常量
<constant name="struts.multipart.maxSize" value="20000000" />
问题就搞定了!