Javascript使用uploadify來實現多檔案上傳_javascript技巧

來源:互聯網
上載者:User

使用uploadify來實現檔案上傳能夠用戶端判斷檔案大小、控制檔案上傳的類型、實現多檔案上傳、顯示進度條等功能,方便易用,相容性較好。

本例是把dwz中整合uploadify功能抽取出來的,可以進行單獨使用,不一定要遭dwz中才能使用,本例只是為了測試,所以使用靜態頁面進行測試:

話不多說,代碼敬上:

2,html頁面的代碼

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>MyHtml.html</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <link href="resources/dwz/uploadify/css/uploadify.css" rel="stylesheet" type="text/css" media="screen" /> <script src="resources/dwz/js/jquery-1.7.2.js" type="text/javascript"></script> <script src="resources/dwz/uploadify/scripts/jquery.uploadify.js" type="text/javascript"></script>  <script src="resources/dwz/uploadify/scripts/errorCode.js" type="text/javascript"></script> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> <style type="text/css" media="screen"> .my-uploadify-button {   background: none;   border: none;   text-shadow: none;   border-radius: 0; }  .uploadify:hover .my-uploadify-button {   background: none;   border: none; }  .fileQueue {   width: 400px;   height: 150px;   overflow: auto;   border: 1px solid #E5E5E5;   margin-bottom: 10px; } </style> <script type="text/javascript">   $(function(){     $('#testFileInput').uploadify({       swf:'resources/dwz/uploadify/scripts/uploadify.swf',       uploader:'servlet/uploadify.do',//上傳的url       formData:{PHPSESSID:'xxx', ajax:1},       buttonText:'請選擇檔案',       fileSizeLimit:'200KB',//設定上傳大小       fileTypeDesc:'*.jpg;*.jpeg;*.gif;*.png;',       fileTypeExts:'*.jpg;*.jpeg;*.gif;*.png;',//允許的尾碼       auto:true,//是否自動上傳       multi:true,       overrideEvents: ['onDialogClose', 'onUploadError', 'onSelectError' ],//重新錯誤資訊的顯示方法       onSelectError: uploadify_onSelectError,       onUploadError: uploadify_onUploadError,       onUploadSuccess: uploadify_onUploadSuccess     });      $('#testFileInput2').uploadify({       swf:'resources/dwz/uploadify/scripts/uploadify.swf',       uploader:'servlet/uploadify.do',       formData:{PHPSESSID:'xxx', ajax:1},       queueID:'fileQueue',       buttonImage:'resources/dwz/uploadify/img/add.jpg',       buttonClass:'my-uploadify-button',       width:102,       auto:false,       fileSizeLimit:'100KB',          fileTypeDesc:'*.jpg;*.jpeg;*.gif;*.png;',        fileTypeExts:'*.jpg;*.jpeg;*.gif;*.png;',        overrideEvents: [ 'onDialogClose','onUploadError', 'onSelectError' ],       onSelectError: uploadify_onSelectError,       onUploadError: uploadify_onUploadError,       onUploadSuccess: uploadify_onUploadSuccess     });   });  </script> </head>  <body>     <!-- 單檔案上傳 -->     <input id="testFileInput" type="file" name="image" />     <div class="divider"></div>     <!-- 多檔案上傳 -->     <input id="testFileInput2" type="file" name="image2" />     <div id="fileQueue" class="fileQueue"></div>     <input type="image" src="resources/dwz/uploadify/img/upload.jpg" onclick="$('#testFileInput2').uploadify('upload', '*');" />     <input type="image" src="resources/dwz/uploadify/img/cancel.jpg" onclick="$('#testFileInput2').uploadify('cancel', '*');" /> </body> </html> 

3,上傳的servlet代碼

package uploadFile;  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;  public class UploadFile extends HttpServlet {    @Override   protected void service(HttpServletRequest request, HttpServletResponse response)       throws ServletException, IOException {     super.service(request, response);   }         @Override   protected void doPost(HttpServletRequest req, HttpServletResponse resp)       throws ServletException, IOException {     //臨時目錄     String basePath = req.getServletContext().getRealPath("upload");     String tempDir = "temp";          File tempFile = new File(basePath + File.separator +tempDir);     if (!tempFile.exists()) {       tempFile.mkdir();     }          DiskFileItemFactory dfc = new DiskFileItemFactory();     dfc.setSizeThreshold(1*1024*1024);//設定臨界值     dfc.setRepository(tempFile);//設定臨時上傳目錄          ServletFileUpload upload = new ServletFileUpload(dfc);     upload.setHeaderEncoding("UTF-8");//設定編碼     // 設定檔案最大值,這裡設定5Mb,5*1024*1024;     upload.setSizeMax(5 * 1024 * 1024);          try {       List fileList = upload.parseRequest(req);       Iterator<FileItem> iterator = fileList.iterator();       while (iterator.hasNext()) {         FileItem item = iterator.next();         String fileName = item.getName();//得到檔案名稱         if (fileName != null) {         //System.out.println(fileName);         //System.out.println(item.getSize());         File sourceFile = new File(basePath+File.separator+fileName);         item.write(sourceFile);         }       }     } catch (FileUploadException e) {       e.printStackTrace();     } catch (Exception e) {       e.printStackTrace();     }          //resp.getWriter().print("上傳成功!");    }         @Override   protected void doGet(HttpServletRequest req, HttpServletResponse resp)       throws ServletException, IOException {     super.doPost(req, resp);   } } 

4,web.xml配置

<servlet>  <servlet-name>upLoadify</servlet-name>  <servlet-class>uploadFile.UploadFile</servlet-class> </servlet> <servlet-mapping>  <servlet-name>upLoadify</servlet-name>  <url-pattern>/servlet/uploadify.do</url-pattern> </servlet-mapping> 

5,uploadify的提示資訊是英文的,為了顯示中文的提示資訊,將其錯誤提示方法進行重新,建立errorCode.js放入在resource/dwz/uploadify/scripts檔案夾下面,並在頁面進行匯入這個js,js代碼如下:

var uploadify_onSelectError = function(file, errorCode, errorMsg) {     var msgText = "上傳失敗\n";     switch (errorCode) {       case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:         //this.queueData.errorMsg = "每次最多上傳 " + this.settings.queueSizeLimit + "個檔案";         msgText += "每次最多上傳 " + this.settings.queueSizeLimit + "個檔案";         break;       case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:         msgText += "檔案大小超過限制( " + this.settings.fileSizeLimit + " )";         break;       case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:         msgText += "檔案大小為0";         break;       case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:         msgText += "檔案格式不正確,僅限 " + this.settings.fileTypeExts;         break;       default:         msgText += "錯誤碼:" + errorCode + "\n" + errorMsg;     }     alert(msgText);   };   var uploadify_onUploadError = function(file, errorCode, errorMsg, errorString) {     // 手工取消不彈出提示     if (errorCode == SWFUpload.UPLOAD_ERROR.FILE_CANCELLED         || errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED) {       return;     }     var msgText = "上傳失敗\n";     switch (errorCode) {       case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:         msgText += "HTTP 錯誤\n" + errorMsg;         break;       case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:         msgText += "上傳檔案丟失,請重新上傳";         break;       case SWFUpload.UPLOAD_ERROR.IO_ERROR:         msgText += "IO錯誤";         break;       case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:         msgText += "安全性錯誤\n" + errorMsg;         break;       case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:         msgText += "每次最多上傳 " + this.settings.uploadLimit + "個";         break;       case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:         msgText += errorMsg;         break;       case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:         msgText += "找不到指定檔案,請重新操作";         break;       case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:         msgText += "參數錯誤";         break;       default:         msgText += "檔案:" + file.name + "\n錯誤碼:" + errorCode + "\n"             + errorMsg + "\n" + errorString;     }     alert(msgText);   }   // return parameters; //}     var uploadify_onUploadSuccess = function(file, data, response) {   alert(file.name + "\n\n上傳成功"); }; 

收工!

原文連結:http://blog.csdn.net/hwt_211/article/details/36888763

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.