下载地址
http://www.uploadify.com/
1, jsp页面
<td><div id="uploadBtn"><input type="file" name="testUploadify" id="<span style="font-family: Arial, Helvetica, sans-serif;">testUploadify</span><span style="font-family: Arial, Helvetica, sans-serif;">"/></div></td></span> <td colspan="1"><div id="fileQueue"></div></td>
2, js层
$("#testUploadify").uploadify({//对应jsp的id 'uploader' : '../js/uploadify/uploadify.swf', //控件flash 'script' : 'upload.do', //后台上传时执行的函数 'scriptData' :{'type': 'testFile1' , 'id':$("#id").val()}, //执行时的参数 'method':'get', //方法 'cancelImg' : '../js/uploadify/cancel.png', //取消按钮图片 'folder' : 'uploadfile', //上传的文件夹 'queueID' : 'fileQueue', //存放信息的那个 'queueSizeLimit' : 1, //允许几个文件 'auto' : true, //自動上传(选择文件后就上传还是submit时上传) 'multi' : false, //允许多个文件 'buttonText' : '', //按钮的文字,好像没啥用 'buttonImg' : '../img/buttonflash.jpg', //上传按钮图片 'width' : 60, //上传按钮WIDTH 'height' : 22, //上传按钮HEIGHT 'removeCompleted' : false, //上传完成后信息消失 'sizeLimit' : 10485760, //大小限制 'onSelect' : function(event,ID,fileObj) { //选择文件的时候 if(fileObj.size > 10485760) { alert("文件太大。"); return false; } if(fileObj.name.length > 100) { alert("文件名太长。"); return false; } }, 'onComplete': function (event, ID, fileObj, response, data) { //文件上传完成的时候 var filename = fileObj.name; var filePath = fileObj.filePath; var tempPath = response; tempPath = tempPath.replace("//","/"); filePath = filePath.replace(""+filename+"",""); filePath = filePath.replace("\jsp",""); filePath = filePath.replace("//","/"); var attachFileSize = 0; if(fileObj.size >= 1048576) { attachFileSize = fileObj.size/1048576; attachFileSize = attachFileSize.toFixed(2) +" MB"; } else if(fileObj.size < 1048576 && fileObj.size >= 1024) { attachFileSize = fileObj.size/1024; attachFileSize = attachFileSize.toFixed(2) +" KB"; } else { attachFileSize = fileObj.size; attachFileSize = attachFileSize.toFixed(2) +" Byte"; } $("#attachPath").val(filePath); }, 'onCancel': function (event, ID, fileObj, response, data) {//取消时执行 $.ajax({ type : "POST", url : "deleteFile.do", async : true, dataType : "String", data : { fileByte : $("#fileByte").val(), }, }); }, });
上传用controller
@Controller public class AttachUploadController extends HttpServlet{ private static Logger logger = LoggerFactory.getLogger(AttachUploadController.class); /** * */ private static final long serialVersionUID = -4991251629513260746L; // @Autowired private AttachDao AttDao; //创建文件夹等 @RequestMapping(value = "*/beforeUpload.do") public void uploadMain(HttpServletRequest request,HttpServletResponse response) throws IOException { try { HttpSession session = request.getSession(); if(session.getAttribute("userId")==null){ response.getWriter().print("login"); }else{ String userId=session.getAttribute("userId").toString(); //设定文件路径 String savePath = request.getSession().getServletContext().getRealPath("/"); savePath = savePath + "/uploadfile/"+userId+"/"; File file = new File(savePath); if (!file.exists()){ file.mkdirs(); }else{ deleteDirectory(savePath); file.mkdirs(); } } } catch (Exception e) { Common.logTrace(logger, e); response.setContentType("text/html;charset=utf-8"); response.getWriter().print("<script lanuage=javascript>alert('" + Common.getMessage("EXC00004") + "');location='javascript:history.go(-1)'</script>"); } } //删除指定目录夏所有文件 public boolean deleteDirectory(String sPath) { File dirFile = new File(sPath); boolean flag = true; File[] files = dirFile.listFiles(); if(files!=null){ for (int i = 0; i < files.length; i++) { //删除子文件 if (files[i].isFile()) { flag = deleteFile(files[i].getAbsolutePath()); if (!flag) break; } //删除子文件夹 else { flag = deleteDirectory(files[i].getAbsolutePath()); if (!flag) break; } } } return true; } //删除文件 public boolean deleteFile(String sPath) { boolean flag = false; File file = new File(sPath); // 删除文件 if (file.isFile() && file.exists()) { file.delete(); flag = true; } return flag; } @SuppressWarnings("unchecked") @RequestMapping(value = "*/upload.do") public void uploadPost(HttpServletRequest request, HttpServletResponse response) throws IOException { try { //session中取得数据 HttpSession session = request.getSession(); if(session.getAttribute("userId")==null){ response.getWriter().print("login"); }else{ String userId=session.getAttribute("userId").toString(); String filetype = request.getParameter("type");//js里面传来的参数 //ファイルのパスを設定する String savePath = request.getSession().getServletContext().getRealPath(Constant.STR_SLUSH); savePath = savePath + "/uploadfile/"+userId+"/"+filetype; File file = new File(savePath+"/temp/"); if (!file.exists()){ file.mkdirs(); }else{ deleteDirectory(savePath); file.mkdirs(); } DiskFileItemFactory fac = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(fac); //设置文件属性 upload.setHeaderEncoding("utf-8"); //生成文件名与尾椎 @SuppressWarnings("rawtypes") List fileList = null; try { fileList = upload.parseRequest(request); } catch (FileUploadException ex) { return; } Iterator<FileItem> it = fileList.iterator(); String name = ""; while (it.hasNext()) { FileItem item = it.next(); if (!item.isFormField()) { name = item.getName(); long size = item.getSize(); String type = item.getContentType(); System.out.println(type +":"+ size); if (name == null || name.trim().equals("")) { continue; } File saveFile = new File(savePath + "/" + name); try { item.write(saveFile); } catch (Exception e) { e.printStackTrace(); } } } response.getWriter().print(savePath + "/" + name); } } catch (Exception e) { Common.logTrace(logger, e); response.setContentType("text/html;charset=utf-8"); response.getWriter().print("<script lanuage=javascript>alert('" + Common.getMessage("EXC00004") + "');location='javascript:history.go(-1)'</script>"); } } }
@SuppressWarnings("resource") @RequestMapping(value = "*/download.do") @ResponseBody public Map<String, Object> doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { Map<String, Object> map = new HashMap<String, Object>(); try { //取得文件 String savepath = request.getSession().getServletContext().getRealPath("/");//取得服务器主路径 String filename = request.getParameter("FileName"); String filepath = Common.getFilepath(request.getParameter("FilePath"));//取得路径 File file = new File(savepath+filepath+"/"+filename); if(file.exists()) { //设置返回属性 response.setContentType(CONTENT_TYPE); response.setContentType("application/x-msdownload"); response.setContentLength((int)file.length()); response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("utf-8"), "iso-8859-1")); //从InputStream生成BufferedInputStream BufferedInputStream buff = new BufferedInputStream(new FileInputStream(file)); //读取文件 byte[] b = new byte[2048]; long k = 0; OutputStream myout = response.getOutputStream(); while(k < file.length()){ int j = buff.read(b,0,2048); k+=j; myout.write(b,0,j); } //关闭流 myout.flush(); return map; } else { map.put("errorMessage", "文件不存在"); return map; } } catch (Exception e) { Common.logTrace(logger, e); map.put("errorMessage", "意料之外的错误"); return map; } }
关于一个页面有多个uploadify控件,设置为非自动上传
发现上传的顺序不可控制,(不遵循jQuery('#uploadify').uploadify('upload','*');执行先后)
但貌似可以控制全部上传完毕后再进行页面跳转?几个uploadify里最后都执行submit()也没问题