uploadfiy插件的多文件上传
jsp页面:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>uploadify多文件上传演示</title> <base href="<%=basePath%>"> <link href="uploadify/uploadify.css" rel="stylesheet" type="text/css"> <script type="text/javascript" src="uploadify/jquery-3.2.1.min.js"></script> <script type="text/javascript" src="uploadify/jquery.uploadify.js"></script> <style type="text/css"> #file_queue { background-color: #FFF; border-radius: 3px; box-shadow: 0 1px 3px rgba(0,0,0,0.25); height: 103px; margin-bottom: 10px; overflow: auto; padding: 5px 10px; width: 300px; } </style> </head> <body> <div id="fileQueue"></div> <table> <tr> <td valign="top" style="width:100px;"><span>上传图片:</span></td> <td valign="top"> <input type="file" name="uploadify" id="uploadify"/> <a href="javascript:$('#uploadify').uploadify('upload','*');">开始上传</a> <a href="javascript:$('#uploadify').uploadify('cancel','*');">取消所有上传</a> </td> </tr> <!-- <tr> <td>图片列表:</td> <td id="attachList"> </td> </tr> --> </table> </body> <script type="text/javascript"> $(document).ready(function(){ $("#uploadify").uploadify({ //设置浏览按钮的高度 ,默认值 height : 30, //设置文件浏览按钮的宽度 width :120, //设置为true当选择文件后就直接上传了,为false需要点击上传按钮才上传 。 auto : false, //浏览按钮的图片的路径 。 buttonImage : 'uploadify/sc.jpg', //浏览按钮的文本。 buttonText : "", //按钮样式 buttonClass : 'none', //文件上传重复性检查程序,检查即将上传的文件在服务器端是否已存在,存在返回1,不存在返回0 //文件上传对象的名称,如果命名为’the_files’,PHP程序可以用$_FILES['the_files']来处理上传的文件对象。 fileObjName : 'uploadify', //上传文件的大小限制 ,如果为整数型则表示以KB为单位的大小, //如果是字符串,则可以使用(B, KB, MB, or GB)为单位,比如’2MB’ //如果设置为0则表示无限制 fileSizeLimit : '1000KB', //这个属性值必须设置fileTypeExts属性后才有效, //用来设置选择文件对话框中的提示文本,如设置fileTypeDesc为“请选择rar doc pdf文件” fileTypeDesc : "请选择txt,doc,xls,pdf,png,rar文件", //设置可以选择的文件的类型,格式如:’*.doc;*.pdf;*.rar’ 。 fileTypeExts : "*", //设置为true时可以上传多个文件。 multi : true, //设置上传队列容器DOM元素的ID,如果为false则自动生成一个队列容器。 queueID : "fileQueue", //队列最多显示的任务数量,如果选择的文件数量超出此限制,将会出发onSelectError事件。 //注意此项并非最大文件上传数量,如果要限制最大上传文件数量,应设置uploadLimit。 removeTimeout : 5, //最大上传文件数量,如果达到或超出此限制将会触发onUploadError事件。 uploadLimit : 10, //如果设置为true,则单个任务上传失败后将返回错误,并重新加入任务队列上传。 requeueErrors : true, //uploadify.swf 文件的相对路径。 swf : 'uploadify/uploadify.swf', //后台处理程序的相对路径。 uploader : 'uploadAttach.action;jsessionid=<%=session.getId()%>', removeCompleted : false, //当Uploadify初始化过程中检测到当前浏览器不支持flash时触发。 onFallback : function(){ alert("您未安装FLASH控件,无法上传图片!请安装FLASH控件后再试。"); }, //选择文件后向队列中添加每个上传任务时都会触发。 /* onSelect : function(file){ $("#fileQueue").text("正在上传..."); $("#fileQueue").show(); }, */ onUploadStart:function(file){ // $(".uploadify-queue-item .cancel a").hide(); }, //上传到服务器,服务器返回相应信息到data里 onUploadSuccess : function(file, data, response){ data = JSON.parse(data); var downloadParam = "fileName="+encodeURI(encodeURI(file.name))+"&id="+data.id+"&attachId="+data.attachId; var delParam = {}; delParam.fileId = file.id, delParam.id = data.id; delParam.attachId = data.attachId; //下载文件 $(".uploadify-queue-item[id="+file.id+"]").find(".fileName") .html("<a style=\"text-decoration:none;\" href='downLoad.action?"+downloadParam+"'>"+file.name+"</a>"); //删除文件 $(".uploadify-queue-item[id="+file.id+"]").find(".cancel") .html("<a style=\"text-decoration:none;\" href=\"javascript:delAttach('"+delParam+"');\" class=\"delete\">删除</a>"); }, onSelectError : function(file, errorCode, errorMsg){ switch(errorCode) { case -100: alert("上传的文件数量已经超出系统限制的"+$('#uploadify').uploadify('settings','queueSizeLimit')+"个文件!"); break; case -110: alert("文件 ["+file.name+"] 大小超出系统限制的"+$('#uploadify').uploadify('settings','fileSizeLimit')+"大小!"); break; case -120: alert("文件 ["+file.name+"] 大小异常!"); break; case -130: alert("文件 ["+file.name+"] 类型不正确!"); break; } } }); }); function delAttach(param){ $('#uploadify').uploadify('cancel',param.fileId); //ajax删除文件 } </script> </html>
后台action
package com.action; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import java.util.UUID; import com.css.core.action.UserAction; import com.css.core.hibernate.HibernateUtil; import com.css.model.shen.EmpAttach; import com.opensymphony.webwork.ServletActionContext; import com.opensymphony.xwork.Action; /** * description:上传附件到本地demo * author:shenqz * 2017-6-20下午2:18:57 */ public class UploadFileAction extends UserAction { private File uploadify; @Override protected String userGo() throws Exception{ EmpAttach attach=new EmpAttach(); String path = ServletActionContext.getServletContext().getRealPath("/upload"); File dir = new File(path); if(!dir.exists() && !dir.isDirectory()){ dir.mkdir(); } String fileName = uploadify.getName(); if(fileName == null || "".equals(fileName)){ result = "上传失败"; return Action.ERROR; } String id = DirEmp.id; String attachId = UUID.randomUUID().toString(); String srcName = fileName; attach.setUuid(attachId); attach.setEmpNo(id); attach.setAttachName(fileName); attach.setFilePath(path); HibernateUtil.currentSession().save(attach); HibernateUtil.currentSession().beginTransaction().commit(); fileName = srcName.substring(srcName.lastIndexOf("\\")+1).substring(0,srcName.lastIndexOf("."))+"&"+attachId+"&"+id; String fileExt = srcName.substring(srcName.lastIndexOf(".")); FileInputStream in = new FileInputStream(uploadify); FileOutputStream out = new FileOutputStream(path+"\\"+fileName+fileExt); byte[] byt = new byte[1024]; int read = 0; while(-1 != (read = in.read(byt))){ out.write(byt, 0, read); } out.flush(); out.close(); /*MultiPartRequestWrapper request = (MultiPartRequestWrapper)ServletActionContext.getRequest(); File[] files = request.getFiles("uploadify"); for(File file:files){ String fileName = file.getName(); if(fileName == null || "".equals(fileName)){ continue; } fileName = fileName.substring(fileName.lastIndexOf("\\")+1); FileInputStream in = new FileInputStream(file); FileOutputStream out = new FileOutputStream(path+"\\"+fileName); byte[] byt = new byte[1024]; int read = 0; while(-1 != (read = in.read(byt))){ out.write(byt, 0, read); } out.flush(); out.close(); }*/ /*HttpServletRequest request = ServletActionContext.getRequest(); DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); if(!ServletFileUpload.isMultipartContent(request)){ result = "上传失败"; return Action.ERROR; } List<FileItem> list = upload.parseRequest(request); for(FileItem item:list){ if(item.isFormField()){ System.out.println(item.getString("UTF-8")); }else{ String fileName = item.getName(); if(fileName == null || "".equals(fileName)){ continue; } fileName = fileName.substring(fileName.lastIndexOf("\\")+1); InputStream in = item.getInputStream(); FileOutputStream out = new FileOutputStream(path+"\\"+fileName); byte[] byt = new byte[1024]; int read = 0; while(-1 != (read = in.read(byt))){ out.write(byt, 0, read); } out.flush(); out.close(); item.delete(); } }*/ result = "{\"id\":\""+id+"\",\"attachId\":\""+attachId+"\"}"; return Action.SUCCESS; } public File getUploadify() { return uploadify; } public void setUploadify(File uploadify) { this.uploadify = uploadify; } }