使用jQuery的ajaxFileUpload控件以ajax方式上传附件有较好的用户体验,在某SSH2项目开发中,使用了ajaxFileUpload实现了附件的上传,具体过程如下:
1、引入及修改ajaxFileUpload.js
<script type="text/javascript" src="<%=basePath%>/js/jquery/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="<%=basePath%>js/ajaxfileupload.js"></script>
为了使得ajaxfileupload支持IE9、IE10,在ajaxfileupload.js中修改createUploadIframe方法(可参考 http://www.jb51.cc/article/p-xjquddto-gy.html)
createUploadIframe: function(id,uri) { //create frame var frameId = 'jUploadFrame' + id; if(window.ActiveXObject) { if(jQuery.browser.version=="9.0"||jQuery.browser.version=="10.0") { io = document.createElement('iframe'); io.id = frameId; io.name = frameId; } else if(jQuery.browser.version=="6.0"||jQuery.browser.version=="7.0"||jQuery.browser.version=="8.0") { var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />'); if(typeof uri== 'boolean'){ io.src = 'javascript:false'; } else if(typeof uri== 'string'){ io.src = uri; } } }
2、form表单及上传控件
form表单设置为:
enctype="multipart/form-data" id="addForm" method="post"上传控件代码为:
<input id="upload" name="upload" size="50" type="file" /> <a class="easyui-linkbutton" iconCls="icon-upload" onclick="ajaxFileUploadCheckType('/sys/file/uploadSysFile.action?fileVo.status=0')" >上传</a> <img src="<%=basePath%>/img/loading_16x16.gif" id="loading" style="display: none;">上传的脚本代码为:
function ajaxFileUploadCheckType(url){ var str=""; var re=new RegExp("(.pdf|.PDF)$"); var upload=$("#upload").val(); if(upload=="") str+="请选择要上传的附件!<br/>"; else if(!re.test(upload.toLowerCase())) str+="请上传PDF格式的文件!!"; if(str=="") ajaxFileUpload(url); else alert(str); } //文件上传 function ajaxFileUpload(url1) { $("#loading") .ajaxStart(function(){ $(this).show(); })//开始上传文件时显示一个等待图片 .ajaxComplete(function(){ $(this).hide(); });//文件上传完成将图片隐藏起来 var fileSelect=$("#fileSelect").val(); //是否选择了文件类型 var url2=url1; if(fileSelect!=undefined&&fileSelect!=null&&fileSelect!=''){ if(url1.indexOf('?')>0) url2=encodeURI(url1+"&fileVo.fileTypeId="+fileSelect); else url2=encodeURI(url1+"?fileVo.fileTypeId="+fileSelect); } var tableName=$("#tableName").val(); if(url2.indexOf('?')>0) url2=encodeURI(url2+"&fileVo.tableName="+tableName); else url2=encodeURI(url2+"?fileVo.tableName="+tableName); var fid=$("#fid").val(); if(url2.indexOf('?')>0) url2=encodeURI(url2+"&fileVo.fid="+fid); else url2=encodeURI(url2+"?fileVo.fid="+fid); $.ajaxFileUpload ( { url:url2,//用于文件上传的服务器端请求地址 secureuri:false,//一般设置为false fileElementId:'upload',//文件上传空间的id属性 <input type="file" id="upload" name="upload" /> // type:'POST',dataType: 'text',//返回值类型 一般设置为json //contentType: "application/x-www-form-urlencoded; charset=utf-8",success: function (data,status) //服务器成功响应处理函数 { //alert((data)); var result=eval('('+data+')'); generateFileList(result,"type"); //使用ajax方式重新长生附件列表 },error: function (data,status,e)//服务器响应失败处理函数 { $.messager.alert('错误提示',"文件上传出现异常,请重新上传或联系管理员!","error"); } } ) return false; }
3、Struts2的XML配置及服务器端处理
XML配置:
<package name="sys.file" namespace="/sys/file" extends="globalpackage"> <action name="uploadSysFile" class="com.cnpc.sys.action.FileUploadAction" method="uploadSysFile"> </action> ……
服务器端Action处理:
package com.cnpc.sys.action; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import com.cnpc.framework.common.action.BaseAction; import com.cnpc.framework.common.exception.GlobalException; import com.cnpc.framework.common.servicefactory.SystemInstance; import com.cnpc.sys.entity.Dictionary; import com.cnpc.sys.entity.Employee; import com.cnpc.sys.service.IDictionaryService; import com.cnpc.sys.service.IEmployeeService; import com.cnpc.sys.service.ISysFileService; import com.cnpc.sys.vo.SysFileVo; import com.cnpc.utils.DateUtils; import com.cnpc.utils.PropertiesTools; import com.cnpc.utils.StrUtils; //附件上传处理类 public class FileUploadAction extends BaseAction { private ISysFileService sysFileService = (ISysFileService) SystemInstance .getInstance().getBean(ISysFileService.class); private IDictionaryService dictionaryService = (IDictionaryService) SystemInstance .getInstance().getBean(IDictionaryService.class); private IEmployeeService employeeService = (IEmployeeService) SystemInstance .getInstance().getBean(IEmployeeService.class); private SysFileVo fileVo; private File upload;// 实际上传文件 private String uploadContentType; // 文件的内容类型 private String uploadFileName; // 上传文件名 private List<SysFileVo> fileVoList; private String message = "你已成功上传文件"; private String tableName; private String year; private List<SysFileVo> volist; public String getYear() { return year; } public void setYear(String year) { this.year = year; } public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public List<SysFileVo> getVolist() { return volist; } public void setVolist(List<SysFileVo> volist) { this.volist = volist; } public SysFileVo getFileVo() { return fileVo; } public void setFileVo(SysFileVo fileVo) { this.fileVo = fileVo; } public File getUpload() { return upload; } public void setUpload(File upload) { this.upload = upload; } public String getUploadContentType() { return uploadContentType; } public void setUploadContentType(String uploadContentType) { this.uploadContentType = uploadContentType; } public String getUploadFileName() { return uploadFileName; } public void setUploadFileName(String uploadFileName) { this.uploadFileName = uploadFileName; } public List<SysFileVo> getFileVoList() { return fileVoList; } public void setFileVoList(List<SysFileVo> fileVoList) { this.fileVoList = fileVoList; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String uploadSysFile() throws GlobalException,IOException { String isAll=fileVo.getIsAll(); Employee emp = employeeService.getEmployeeByID(getSessionContainer().getUserId()); if (fileVo == null) { fileVo = new SysFileVo(); } String[] str = saveUpload(); fileVo.setFileName(str[0]); fileVo.setVirtualName(str[1]); fileVo.setFilePath(str[2].replace("\\","\\\\")); if (fileVo != null) { if (fileVo.getEmpid() == null) { Integer empid = emp.getEmpid(); fileVo.setEmpid(empid); } if (fileVo.getUploadTime() == null) { fileVo.setUploadTime(DateUtils.format(new Date(System .currentTimeMillis()),DateUtils.formatStr_yyyyMMdd)); } if (fileVo.getTableName() == null) { fileVo.setTableName(tableName); } if(fileVo.getYear()==null){ if(year==null) year=DateUtils.getYear(); fileVo.setYear(year); } if(fileVo.getIid()==null){ fileVo.setIid(emp.getInstitute().getIid()); } fileVo = sysFileService.addSysFileVo(fileVo); } if (fileVoList == null) { fileVoList = new ArrayList<SysFileVo>(); } fileVo.setIsAll(isAll); if(fileVo.getIsAll()!=null&&fileVo.getIsAll().equals("1")){ fileVoList = sysFileService.getAllSysFileByInfoId( fileVo.getTableName(),fileVo.getFid()); }else{ fileVoList = sysFileService.getSysFileByInfoId( fileVo.getTableName(),null,fileVo.getFid(),fileVo.getStatus()); } String jsonStr = getJsonForFileList(fileVoList); HttpServletResponse response = getCurrentResponse(); HttpServletRequest request=getCurrentRequest(); request.setCharacterEncoding(ENCODING); response.setCharacterEncoding(ENCODING); response.setContentType("text/html"); outPutString(jsonStr); return NONE; } public String getJsonForFileList(List<SysFileVo> filelist) { if (filelist == null) return "[]"; StringBuffer buffer = new StringBuffer("["); for (SysFileVo vo : filelist) { buffer.append("{'id':'" + vo.getFileId() + "','name':'" + vo.getFileName() + "','path':'" + vo.getFilePath().replace("\\","\\\\") + "','typeName':'" + vo.getFileTypeName() + "','typeid':'" + vo.getFileTypeId() + "','status':'" + vo.getStatus() + "'},"); } if (buffer.length() > 1) buffer = new StringBuffer(buffer.substring(0,buffer.length() - 1)); buffer.append("]"); return buffer.toString(); } @SuppressWarnings("deprecation") public String[] saveUpload() throws IOException { String[] result = new String[3]; try { if (uploadFileName != null && !"".equals(uploadFileName)) { String trueName = uploadFileName.substring(uploadFileName .lastIndexOf("/") + 1,uploadFileName.length()); String fileName = new Date().getTime() + com.cnpc.utils.FileUtils.getExtention(uploadFileName); String path = PropertiesTools.getPropertiesValueByFileAndKey( "globalParameters.properties","uploadPath"); String targetDirectory = path; String targetFileName = fileName; // 以服务器的文件保存地址和原文件名建立上传文件输出流 FileOutputStream fos = new FileOutputStream(path + "\\" + fileName); // 以上传文件建立一个文件上传流 FileInputStream fis = new FileInputStream(upload); // 将上传文件的内容写入服务器 byte[] buffer = new byte[1024]; int len = 0; while ((len = fis.read(buffer)) > 0) { fos.write(buffer,len); } fis.close(); fos.flush(); result[0] = trueName; result[1] = fileName; result[2] = path + "\\" + fileName; } } catch (Exception e) { e.printStackTrace(); message = "对不起,文件上传失败了!!!!"; } return result; } public String deleteSysFile() throws GlobalException,IOException { if (fileVo != null && fileVo.getFileId() != null) { SysFileVo deleteVo = sysFileService.getSysFileByID(fileVo .getFileId()); deleteFile(deleteVo.getFilePath()); sysFileService.deleteSysFileByVoId(deleteVo.getFileId()); if (fileVoList == null) { fileVoList = new ArrayList<SysFileVo>(); } if(fileVo.getIsAll()!=null&&fileVo.getIsAll().equals("1")){ fileVoList = sysFileService.getAllSysFileByInfoId( deleteVo.getTableName(),deleteVo.getFid()); }else{ fileVoList = sysFileService.getSysFileByInfoId(deleteVo.getTableName(),deleteVo.getFid(),deleteVo.getStatus()); } } String jsonStr = getJsonForFileList(fileVoList); HttpServletResponse response = getCurrentResponse(); HttpServletRequest request=getCurrentRequest(); request.setCharacterEncoding(ENCODING); response.setCharacterEncoding(ENCODING); response.setContentType("text/html"); outPutString(jsonStr); return NONE; } public String downloadFile() throws Exception { SysFileVo filevo = sysFileService .getsysfilebypath(fileVo.getFilePath()); HttpServletResponse response = getCurrentResponse(); HttpServletRequest request=getCurrentRequest(); request.setCharacterEncoding(ENCODING); response.setCharacterEncoding(ENCODING); response.setContentType("text/html"); if (filevo != null) { setCurrentAttribute("filename",filevo.getFileName()); setCurrentAttribute("fileurl",filevo.getFilePath()); } else { setCurrentAttribute("filename",fileVo.getFileName()); setCurrentAttribute("fileurl",fileVo.getFilePath()); } return "download"; } public void deleteFile(String path) { String targetDirectory = ServletActionContext.getRequest().getRealPath( ""); File target = new File(targetDirectory,path); if (target.exists()) { target.delete(); } else { System.out.println("文件不存在"); } } public String ajaxCheckFile() throws IOException { String typeids = getCurrentParameter("typeids"); String dictCode = getCurrentParameter("dictCode"); // List<SysFileVo> filelist=sysFileService.getSysFileByInfoId(tabName,// Integer.valueOf(id)); String[] arrType = null; if (!StrUtils.isEmpty(typeids)) arrType = typeids.substring(0,typeids.length() - 1).split(","); List<Dictionary> dictlist = dictionaryService .getDictsByDictCode(dictCode); String str = ""; boolean isExist = false; for (Dictionary dict : dictlist) { isExist = false; if (dict.getIsCheck() != null && dict.getIsCheck().equals("1")) { if (arrType != null) { for (String typeid : arrType) { if (dict.getDictid().equals(Integer.valueOf(typeid))) { isExist = true; break; } } } if (!isExist) str += dict.getDictName() + "不能为空!\r\n"; } } outPutString(str); return NONE; } }
FileUploadAction包含了附件上传、删除、生成json附件列表功能,该处理类是直接复制、粘贴项目源代码而来,如果使用,请按照需求进行增删。