<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>ajaxFileUpload文件上传例子</title> <script type="text/javascript" src="<%=baseURL%>/kinth/js/ajaxfileupload.js"></script> <script type="text/javascript"> var flag=0; //flag作用:分两种情况提交信息,如果是修改操作,没有修改上传文件,只修改其他字段的信息时点保存也能提交信息 function uploadFile(){ $.ajaxFileUpload({ url:baseURL+ "/fileCatalog.do?method=save", //需要链接到服务器地址 secureuri:true, fileElementId:'file', //文件选择框的id属性 success: function(data, status){ var results = $(data).find('body').html(); var obj = eval("("+results+")"); $("#fileSize").val(obj.fileSize); $("#fileUrl").val(obj.fileUrl); $('#fileCatalogForm').submit(); },error: function (data, status, e){ showDialogWithMsg('ideaMsg','提示','文件错误!'); } }); } function getFileName(obj) { flag=1; var pos = -1; if(obj.value.indexOf("/") > -1){ pos = obj.value.lastIndexOf("/")*1; }else if(obj.value.indexOf("\\") > -1){ pos = obj.value.lastIndexOf("\\")*1; } var fileName = obj.value.substring(pos+1); $("#fileName").val(fileName); $('.files').text(fileName); } function ev_save(){ if(submitMyForm('fileCatalogForm')){ if(flag==0){ $('#fileCatalogForm').submit(); }else{ uploadFile(); } } } function ev_back(){ window.location.href=baseURL+'/fileCatalog.do?method=list'; } </script> </head> <body> <html:form styleId="fileCatalogForm" action="/fileCatalog.do?method=save&fileFlag=true" method="post" enctype="application/x-www-form-urlencoded" style="text-align:left;"> <table> <tr> <td>附件上传:</td> <td style="text-align:left;" id="fileTd"> <input type="file" name="file" id="file" onChange="getFileName(this);" /><br /> </td> <td colspan="2" class="tdr"> <ol class=files> <c:if test="${entity.resourceId != null && entity.resourceId != ''}"><li> ${entity.fileName} 上传成功</li></c:if> </ol> </td> </tr> <c:if test="${entity.resourceId == null || entity.resourceId == ''}"> <input type="text" name="fileSize" id="fileSize" > </c:if> <input type="hidden" id="fileUrl" name="fileUrl" value="${entity.fileUrl}" </table> </html:form> </body>
?
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>jqueryUploadify文件上传例子</title> <script type="text/javascript" src="<%=baseURL %>/kinth/common/js/jquery.validate.js" ></script> <!-- 附件上传 --> <link href="<%=baseURL%>/kinth/common/jqueryUpload/uploadify.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="<%=baseURL%>/kinth/common/jqueryUpload/swfobject.js"></script> <script type="text/javascript" src="<%=baseURL%>/kinth/common/jqueryUpload/jquery.uploadify.v2.0.3.min.js"></script> <script type="text/javascript"> var flag=0; $(document).ready(function() { $("#files").uploadify({ 'uploader' : '<%=baseURL%>/kinth/common/jqueryUpload/uploadify.swf', 'script' : '<%=baseURL%>/fileCatalog.do?method=fileUpload', 'cancelImg' : '<%=baseURL%>/kinth/common/jqueryUpload/cancel.png', 'queueID' : 'fileQueue', 'scriptData' : {'resourceId' : $('#resourceId').val()}, 'auto' : false, 'multi' : false, 'buttonText' : 'Brower file', onComplete: function (evt, queueID, fileObj, response, data) { $('#fileUrl').attr("value",response); $('<li></li>').appendTo('.files').text(fileObj.name+"上传成功"); $('#fileCatalogForm').submit(); }, onSelect: function(evt,queueID, fileObj){ flag=1; var filename = fileObj.name; $('#fileName').attr("value",filename.substring(0,filename.lastIndexOf("."))); $('#fileSize').attr("value",fileObj.size); }, onError: function(a, b, c, d) { alert("文件上传失败"); } }); }); function myuploadifyUpload(){ $('#files').uploadifyUpload(); } function ev_save(){ if(submitMyForm('fileCatalogForm')){ if(flag==0){ $('#fileCatalogForm').submit(); }else{ myuploadifyUpload(); } } } </script> </head> <body> <html:form styleId="fileCatalogForm" action="/fileCatalog.do?method=save" method="post" enctype="application/x-www-form-urlencoded" style="text-align:left;"> <table> <tr> <td>附件上传:</td> <td style="text-align:left;" > <input type="file" name="files" id="files" /><br /> ${entity.fileName} <input type="hidden" id="fileUrl" name="fileUrl" value="${entity.fileUrl}" /> <div id="fileQueue"></div> <ol class=files></ol> <p> <a href="javascript:jQuery('#files').uploadifyClearQueue()">取消所有上传</a> </p> </td> </tr> <c:if test="${entity.resourceId == null || entity.resourceId == ''}"> <input type="text" name="fileSize" id="fileSize" /> <input type="text" id="fileName" name="fileName" /> </c:if> <input type="hidden" id="fileUrl" name="fileUrl" value="${entity.fileUrl}" </table> </html:form> </body>
?
package com.kinth.hddpt.file.action; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.upload.FormFile; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import com.gdcn.bpaf.common.base.search.MyCriteria; import com.gdcn.bpaf.common.base.search.MyCriteriaFactory; import com.gdcn.bpaf.common.base.service.BaseService; import com.gdcn.bpaf.common.helper.PagerList; import com.gdcn.bpaf.common.helper.WebHelper; import com.gdcn.bpaf.common.taglib.SplitPage; import com.gdcn.bpaf.security.model.LogonVO; import com.gdcn.components.appauth.common.helper.DictionaryHelper; import com.kinth.common.base.action.BaseAction; import com.kinth.hddpt.file.action.form.FileCatalogForm; import com.kinth.hddpt.file.model.FileCatalog; import com.kinth.hddpt.file.service.FileCatalogService; import com.kinth.hddpt.file.util.MyZTreeNode; /** * <p> * description: “文件上传的Struts层请求处理类” * </p> * @date : 2013-1-14 */ public class FileCatalogAction extends BaseAction<FileCatalog> { @SuppressWarnings("unused") private static Log log = LogFactory.getLog(FileCatalogAction.class); // 日志记录 private FileCatalogService fileCatalogService; // 删除记录的同时删除相应文件 public ActionForward fileDelete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String[] id = request.getParameterValues("resourceId"); if (id != null && id[0].contains(",")) { id = id[0].split(","); } String[] fileUrls = new String[id.length]; for (int j = 0; j < id.length; j++) { fileUrls[j] = fileCatalogService.findObject(id[j]).getFileUrl(); if (!isEmpty(fileUrls[j])) { // 如果该文件夹不存在则创建一个uptext文件夹 File fileup = new File(fileUrls[j]); if (fileup.exists() || fileup != null) { fileup.delete(); } } fileCatalogService.deleteObject(id[j]); } setAllActionInfos(request); return list(mapping, form, request, response); } @Override public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String id = request.getParameter("resourceId"); Boolean fileFlag = Boolean.valueOf(request.getParameter("fileFlag")); if(fileFlag != null && fileFlag == true){ return super.save(mapping, form, request, response); }else{ String fileUrl = this.fileUpload(form, request, id, fileFlag); response.setContentType("text/html"); response.setCharacterEncoding("GBK"); response.setHeader("Charset", "GBK"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write(fileUrl); response.getWriter().flush(); } return null; } @SuppressWarnings("unchecked") public String fileUpload(ActionForm form,HttpServletRequest request,String id,Boolean fileFlag) throws FileNotFoundException, IOException{ request.setCharacterEncoding("GBK"); String basePath = getServlet().getServletConfig().getServletContext().getRealPath("")+"/"; String filePath = "uploads/"; // 获取项目根路径 ; /*注释部分对应jquery upload uploadify插件的后台代码,只是还存在编码问题,默认为utf-8 String savePath = getServlet().getServletConfig().getServletContext().getRealPath(""); // 获取项目根路径 savePath = savePath + "\\uploads\\"; //读取上传来的文件信息 Hashtable<String, FormFile> fileHashtable = form.getMultipartRequestHandler().getFileElements(); Enumeration<String> enumeration = fileHashtable.keys(); enumeration.hasMoreElements(); String key = (String) enumeration.nextElement(); FormFile formFile = (FormFile)fileHashtable.get(key); String filename = formFile.getFileName().trim(); //文件名 filename = new EncodeChange().changeCode(filename); String filetype = filename.substring(filename.lastIndexOf(".") + 1);//文件类型 savePath = savePath+filetype+"\\"; System.out.println("path:"+savePath); String realPath = savePath + filename; //真实文件路径 //如果该文件夹不存在则创建一个文件夹 File fileup = new File(savePath); if(!fileup.exists()||fileup==null){ fileup.mkdirs(); } if (!filename.equals("")) { // 在这里上传文件 InputStream is = formFile.getInputStream(); OutputStream os = new FileOutputStream(realPath); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = is.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); is.close(); //如果是修改操作,则删除原来的文件 String id = request.getParameter("resourceId"); if (!isEmpty(id)) { FileCatalog fileCatalog = fileCatalogService.findObject(id); String fileUrl = fileCatalog.getFileUrl(); if (!isEmpty(fileUrl)) { File filedel = new File(fileUrl); if(filedel.exists()||filedel!=null){ filedel.delete(); } } request.setAttribute("entity", fileCatalog); } response.getWriter().print(realPath);// 向页面端返回结果信息 }*/ // 读取上传来的文件信息 Hashtable<String, FormFile> fileHashtable = form.getMultipartRequestHandler().getFileElements(); Enumeration<String> enumeration = fileHashtable.keys(); enumeration.hasMoreElements(); String key = (String) enumeration.nextElement(); FormFile formFile = (FormFile) fileHashtable.get(key); String filename = formFile.getFileName().trim(); // 文件名 String filetype = filename.substring(filename.lastIndexOf(".") + 1);// 文件类型 Integer fileSize = formFile.getFileSize(); filePath += Calendar.getInstance().get(Calendar.YEAR)+"/"+filetype+"/" ; String realPath = basePath+filePath+filename; // 真实文件路径 if (!filename.equals("")) { // 如果是修改操作,则删除原来的文件 if (!isEmpty(id)) { FileCatalog fileCatalog = fileCatalogService.findObject(id); String fileUrl = fileCatalog.getFileUrl(); if (!isEmpty(fileUrl)) { fileUrl = basePath + fileUrl; File filedel = new File(fileUrl); if (filedel.exists() || filedel != null) { filedel.delete(); } } request.setAttribute("entity", fileCatalog); } // 如果该文件夹不存在则创建一个文件夹 File fileup = new File(basePath+filePath); if (!fileup.exists() || fileup == null) { fileup.mkdirs(); } // 在这里上传文件 InputStream is = formFile.getInputStream(); OutputStream os = new FileOutputStream(realPath); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = is.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); is.close(); } filePath += filename; String result = "{\"fileName\":\""+filename+"\",\"fileType\":\""+filetype+"\",\"fileSize\":"+fileSize+",\"fileUrl\":\""+filePath+"\"}"; return result; } public FileCatalogService getFileCatalogService() { return fileCatalogService; } public void setFileCatalogService(FileCatalogService fileCatalogService) { this.fileCatalogService = fileCatalogService; } }
?
package com.kinth.hddpt.file.action; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /* jqueryUploadify文件上传servlet类,写了此类就可以不用到action中写fileUpload方法了,只是不能把上传的文件保存到数据库中 这种方法记得配置web.xml哦, 如 <!--附件上传开始--> ? <servlet> ?? <servlet-name>Upload</servlet-name> ?? <servlet-class> com.kinth.hddpt.file.action.UploadController </servlet-class> </servlet> ? <servlet-mapping> <servlet-name>Upload</servlet-name> ?? <url-pattern>/servlet/fileUpload</url-pattern> ? </servlet-mapping> ????? <!--附件上传结束--> ????? */ public class UploadController extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); String savePath = this.getServletConfig().getServletContext().getRealPath(""); savePath = savePath + "/uploads/resourses/"; DiskFileItemFactory fac = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(fac); upload.setHeaderEncoding("utf-8"); List fileList = null; try { fileList = upload.parseRequest(request); } catch (FileUploadException ex) { ex.printStackTrace(); } Iterator<FileItem> it = fileList.iterator(); String name = ""; String extName = ""; String category = ""; while (it.hasNext()) { FileItem item = it.next(); if (item.isFormField()) { if ("category".equals(item.getFieldName())) { category = item.getString("utf-8"); } } else if (!item.isFormField()) { name = item.getName(); if (name == null || name.trim().equals("")) { continue; } // 扩展名格式: if (name.lastIndexOf(".") >= 0) { extName = name.substring(name.lastIndexOf(".")); } savePath = savePath + category + "/"; File f1 = new File(savePath); if (!f1.exists()) { f1.mkdirs(); } File saveFile = new File(savePath + name); try { item.write(saveFile); } catch (Exception e) { e.printStackTrace(); } } } response.getWriter().print(name + " 上传成功"); } }
?