uploadify上传插件完整Demo(包括后台)
生活随笔
收集整理的這篇文章主要介紹了
uploadify上传插件完整Demo(包括后台)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
uploadify上傳插件完整Demo,項目開發(fā)中被uploadify坑了一把,一怒之下寫了前后臺完整的示例,旨在徹底解決uploadify的問題!
示例文件Demo下載路徑:http://download.csdn.net/download/ljj2312/10134797 ??
index.html
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>UploadiFive Test</title> <script src="jquery.min.js" type="text/javascript"></script> <script src="jquery.uploadify.min.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="uploadify.css"> <style type="text/css"> body {font: 13px Arial, Helvetica, Sans-serif; } </style> </head><body><h1>Uploadify Demo</h1><form><div id="queue"></div><input id="file_upload" name="file_upload" type="file" multiple="true"></form><p><p><a href="javascript:$('file_upload').uploadifyUpload()">upload</a>|<a href="javascript:$('file_upload').uploadifyClearQueue()">cacle</a></p></p><script type="text/javascript">$(function() {$('#file_upload').uploadify({'queueID' : 'queue',//上傳進(jìn)度展示'buttonText': 'selectFile..','langFile':'uploadifyLang_zh.js','swf': 'uploadify.swf','formData': {'pid' : 'portal','token': 'portal','filedesc':''},'method':'Post','scriptAccess' : 'always' ,'uploader' : 'http://10.**.23.***:8821/mgr/voice/file/v1/upload','auto': true,'onUploadStart' : function(file) {alert('Starting to upload ' + file.name);},'onUploadSuccess' : function(file, data, response) {alert('The file ' + file.name + ' was successfully uploaded with a response of ' + response + ':' + data);},'onUploadError' : function(file, errorCode, errorMsg, errorString) {alert('The file ' + file.name + ' could not be uploaded: ' + errorString);},onComplete: function (evt, queueID, fileObj, response, data) {alert(response);// $('<li></li>').appendTo('#fileContent'+id).html(response);}});});</script> </body> </html>后臺上傳方法:
FileUploadServlet.java
package com.gsww.open.controller;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;import com.gsww.open.common.SpringContextHolder; import com.gsww.open.entity.sys.SysUserSession; import com.gsww.open.entity.upload.ShFileData; import com.gsww.open.service.upload.ShFileDataService; import com.gsww.open.util.StringHelper; import com.gsww.open.util.TimeHelper;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*/@Overridepublic void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String fileSize = "";// 得到上傳文件的保存目錄,將上傳的文件存放于WEB-INF目錄下,不允許外界直接訪問,保證上傳文件的安全// E:/upload/dataString savePath =this.getServletContext().getRealPath("/WEB-INF/upload");// 上傳時生成的臨時文件保存目錄String tempPath =this.getServletContext().getRealPath("/WEB-INF/temp");File tmpFile = new File(tempPath);if (!tmpFile.exists()) {// 創(chuàng)建臨時目錄tmpFile.mkdir();}// 消息提示String message = "";try {// 使用Apache文件上傳組件處理文件上傳步驟:// 1、創(chuàng)建一個DiskFileItemFactory工廠DiskFileItemFactory factory = new DiskFileItemFactory();// 設(shè)置工廠的緩沖區(qū)的大小,當(dāng)上傳的文件大小超過緩沖區(qū)的大小時,就會生成一個臨時文件存放到指定的臨時目錄當(dāng)中。factory.setSizeThreshold(1024 * 100);// 設(shè)置緩沖區(qū)的大小為100KB,如果不指定,那么緩沖區(qū)的大小默認(rèn)是10KB// 設(shè)置上傳時生成的臨時文件的保存目錄factory.setRepository(tmpFile);// 2、創(chuàng)建一個文件上傳解析器ServletFileUpload upload = new ServletFileUpload(factory);// 監(jiān)聽文件上傳進(jìn)度upload.setProgressListener(new ProgressListener() {public void update(long pBytesRead, long pContentLength,int arg2) {}});// 解決上傳文件名的中文亂碼upload.setHeaderEncoding("UTF-8");// 3、判斷提交上來的數(shù)據(jù)是否是上傳表單的數(shù)據(jù)if (!ServletFileUpload.isMultipartContent(request)) {// 按照傳統(tǒng)方式獲取數(shù)據(jù)return;}// 設(shè)置上傳單個文件的大小的最大值,目前是設(shè)置為1024*1024字節(jié),也就是1MBupload.setFileSizeMax(1024 * 1024 * 5);// 設(shè)置上傳文件總量的最大值,最大值=同時上傳的多個文件的大小的最大值的和,目前設(shè)置為10MBupload.setSizeMax(1024 * 1024 * 10);// 4、使用ServletFileUpload解析器解析上傳數(shù)據(jù),解析結(jié)果返回的是一個List<FileItem>集合,每一個FileItem對應(yīng)一個Form表單的輸入項List<FileItem> list = upload.parseRequest(request);for (FileItem item : list) {// 如果fileitem中封裝的是普通輸入項的數(shù)據(jù)//if (item.isFormField()) {//String name = item.getFieldName();// 解決普通輸入項的數(shù)據(jù)的中文亂碼問題//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;}// 注意:不同的瀏覽器提交的文件名是不一樣的,有些瀏覽器提交上來的文件名是帶有路徑的,如:// c:\a\b\1.txt,而有些只是單純的文件名,如:1.txt// 處理獲取到的上傳文件的文件名的路徑部分,只保留文件名部分filename = filename.substring(filename.lastIndexOf("\\") + 1);// 得到上傳文件的擴(kuò)展名String fileExtName = filename.substring(filename.lastIndexOf(".") + 1);if (!StringHelper.isEmptyString(fileExtName)) {fileExtName = fileExtName.toLowerCase();}// 如果需要限制上傳的文件類型,那么可以通過文件的擴(kuò)展名來判斷上傳的文件類型是否合法// 獲取item中的上傳文件的輸入流InputStream in = item.getInputStream();// 得到文件保存的名稱String saveFilename = makeFileName(filename);// 得到文件的保存目錄String realSavePath = makePath(saveFilename, savePath);// 創(chuàng)建一個文件輸出流FileOutputStream out = new FileOutputStream(realSavePath + "\\" + saveFilename);// 創(chuàng)建一個緩沖區(qū)byte buffer[] = new byte[1024];// 判斷輸入流中的數(shù)據(jù)是否已經(jīng)讀完的標(biāo)識int len = 0;// 循環(huán)將輸入流讀入到緩沖區(qū)當(dāng)中,(len=in.read(buffer))>0就表示in里面還有數(shù)據(jù)while ((len = in.read(buffer)) > 0) {// 使用FileOutputStream輸出流將緩沖區(qū)的數(shù)據(jù)寫入到指定的目錄(savePath +// "\\" + filename)當(dāng)中out.write(buffer, 0, len);}// 關(guān)閉輸出流out.close(); // 刪除處理文件上傳時生成的臨時文件 //item.delete();// message = "文件上傳成功!";// 關(guān)閉輸入流in.close();/* 保存文件關(guān)系 */SysUserSession sysUserSession =(SysUserSession) request.getSession().getAttribute("sysUserSession");ShFileData shFileData = new ShFileData();shFileData.setFileSaveName(saveFilename);shFileData.setFileName(filename);shFileData.setFileSize(fileSize);shFileData.setFilePath(realSavePath);shFileData.setFileType(fileExtName);shFileData.setFileCreatId(sysUserSession.getAccountId());shFileData.setFileCreatName(sysUserSession.getUserName());shFileData.setFileCreatDate(TimeHelper.getCurrentTime());shFileData.setFileCreatState("00A");shFileDataService.save(shFileData);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", "單個文件超出最大值!!!");return;} catch (FileUploadBase.SizeLimitExceededException e) {request.setAttribute("message", "上傳文件的總的大小超出限制的最大值!!!");return;} catch (Exception e) {message = "文件上傳失敗!";request.setAttribute("message", "文件上傳失敗!");}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// 為防止文件覆蓋的現(xiàn)象發(fā)生,要為上傳文件產(chǎn)生一個唯一的文件名return UUID.randomUUID().toString() + "_" + filename;}private String makePath(String filename, String savePath) {//int dir1 = hashcode & 0xf; // 0--15//int dir2 = (hashcode & 0xf0) >> 4; // 0-15// 構(gòu)造新的保存目錄// String dir = savePath + "\\" + dir1 + "\\" + dir2; //upload\2\3// upload\3\5String dir = savePath;// File既可以代表文件也可以代表目錄File file = new File(dir);// 如果目錄不存在if (!file.exists()) {// 創(chuàng)建目錄file.mkdirs();}return dir;} }注意:可能存在tomcat跨域問題,需要在Tomcat 7.0\webapps\ROOT路徑下放置crossdomain.xml即可。
示例文件Demo下載路徑:http://download.csdn.net/download/ljj2312/10134797
請關(guān)注我微信公眾號:lijun807882378
總結(jié)
以上是生活随笔為你收集整理的uploadify上传插件完整Demo(包括后台)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于 Flink、ClickHouse
- 下一篇: phpcms v9模板制作教程(转载)