从一个异常引起的,TypeError: $("#file_upload").uploadify is not a function
,其实就是使用uploadify组件上传文件,但是一直报莫名其妙的错误。网上众说纷纭…在此记录并上传调试好的源码。
【1】uploadify组件
uploadify官网:http://www.uploadify.com/ 但是从这里下载好像付费,文章末尾会附上源码和插件下载地址。
页面源码
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>UploadiFive Test</title> <link rel="stylesheet" type="text/css" href="/UeditorWeb/uploadifive.css"/> <script type="text/javascript" src="/UeditorWeb/jquery.min.js"></script> <script type="text/javascript" src="/UeditorWeb/jquery.uploadifive.min.js"></script> <style type="text/css"> body { font: 13px Arial, Helvetica, Sans-serif; } .uploadifive-button { float: left; margin-right: 10px; } #queue { border: 1px solid #E5E5E5; height: 177px; overflow: auto; margin-bottom: 10px; padding: 0 3px 3px; width: 300px; } </style> </head> <body> <form> <div id="queue"></div> <input id="file_upload" name="file_upload" type="file" multiple="true"> <a style="position: relative; top: 8px;" href="javascript:$('#file_upload').uploadifive('upload')">Upload Files</a> </form> <script type="text/javascript"> $(function() { $('#file_upload').uploadifive({ 'auto' : false, 'formData' : { 'timestamp' : '111', 'token' : '111' }, 'queueID' : 'queue', 'uploadScript' : '/UeditorWeb/upload', 'onUploadComplete' : function(file, data) { console.log(data); } }); }); </script> </body> </html>
【2】修改后的Huploadify组件
页面源码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <link rel="stylesheet" type="text/css" href="/UeditorWeb/Huploadify.css"/> <script type="text/javascript" src="/UeditorWeb/jquery.js"></script> <script type="text/javascript" src="/UeditorWeb/jquery.Huploadify.js"></script> <style type="text/css"> </style> <script type="text/javascript"> $(function(){ $('#upload').Huploadify({ auto:true, fileTypeExts:'*.jpg;*.png;*.exe', multi:true, formData:{pid:'portal',token:'portal',filedesc:''}, fileSizeLimit:9999, showUploadedPercent:true,//是否实时显示上传的百分比,如20% showUploadedSize:true, removeTimeout:9999999, uploader : '/UeditorWeb/upload', onUploadStart:function(){ //alert('开始上传'); }, onInit:function(){ //alert('初始化'); }, onUploadComplete:function(){ //alert('上传完成'); }, onUploadSuccess: function(file, data, response) { alert(data); }, onDelete:function(file){ console.log('删除的文件:'+file); console.log(file); } }); }); </script> </head> <body> <div id="upload"></div> </body> </html>
每次选择文件都会直接上传,下面会有一个进度条示意。
后台对应代码
就是很常见的文件上传。
package com.web.servlet; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.text.DecimalFormat; import java.util.List; import java.util.UUID; 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.FileUploadBase; import org.apache.commons.fileupload.ProgressListener; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class FileUploadServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 8382832509729035231L; // private ShFileDataService shFileDataService = SpringContextHolder.getBean("shFileDataService"); /** * Constructor of the object. */ public FileUploadServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String fileSize = ""; String savePath = this.getServletContext().getRealPath("/WEB-INF/upload"); String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp"); File tmpFile = new File(tempPath); if (!tmpFile.exists()) { tmpFile.mkdir(); } String message = ""; try { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024 * 100); factory.setRepository(tmpFile); ServletFileUpload upload = new ServletFileUpload(factory); upload.setProgressListener(new ProgressListener() { public void update(long pBytesRead, long pContentLength, int arg2) { } }); upload.setHeaderEncoding("UTF-8"); if (!ServletFileUpload.isMultipartContent(request)) { return; } upload.setFileSizeMax(1024 * 1024 * 5); upload.setSizeMax(1024 * 1024 * 10); List<FileItem> list = upload.parseRequest(request); for (FileItem item : list) { //if (item.isFormField()) { //String name = item.getFieldName(); //String value = item.getString("UTF-8"); // value = new // } else {// ���fileitem�з�װ�����ϴ��ļ� String filename = item.getName(); Long filesizeNum = (Long) item.getSize(); if (filesizeNum > 0) { DecimalFormat df = new DecimalFormat("####.00"); float size = (float) filesizeNum / 1024; fileSize = df.format(size); } if (filename == null || filename.trim().equals("")) { continue; } filename = filename.substring(filename .lastIndexOf("\\") + 1); String fileExtName = filename.substring(filename .lastIndexOf(".") + 1); InputStream in = item.getInputStream(); String saveFilename = makeFileName(filename); String realSavePath = makePath(saveFilename, savePath); FileOutputStream out = new FileOutputStream( realSavePath + "\\" + saveFilename); byte buffer[] = new byte[1024]; int len = 0; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } out.close(); in.close(); String href = realSavePath+"\\"+saveFilename; StringBuilder resultHtml = new StringBuilder(); resultHtml.append(" <li id='file_SWFUpload_5_0' style='font-size: 16px;margin-left: 25px;padding: 5px;'> "); resultHtml.append(" <span class='attch-name'>"+ filename); resultHtml.append(" <span class='attch-size'>" + fileSize + "KB</span><span class='attch-state' style='color:#c1c1c1'>(���)</span>"); resultHtml.append(" <a style='color: #178be2' target='_blank' href='"+href+"' class='attch-dload'>����</a>"); // resultHtml.append(" <a style='color: #178be2' id='"+shFileData.getFileId()+"' class='attch-delete'>ɾ��</a>"); resultHtml.append(" </li>"); response.getWriter().write(resultHtml.toString()); //} } } catch (FileUploadBase.FileSizeLimitExceededException e) { request.setAttribute("message", "the file is too big"); return; } catch (FileUploadBase.SizeLimitExceededException e) { request.setAttribute("message", "the file is too big"); return; } catch (Exception e) { message = "file upload fail"; request.setAttribute("message", "file upload fail"); } request.setAttribute("message", message); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { } private String makeFileName(String filename) { // 2.jpg return UUID.randomUUID().toString() + "_" + filename; } private String makePath(String filename, String savePath) { String dir = savePath; File file = new File(dir); if (!file.exists()) { file.mkdirs(); } return dir; } }
项目和组件下载地址
下载内容示意: