DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> Javascript使用uploadify來實現多文件上傳
Javascript使用uploadify來實現多文件上傳
編輯:關於JavaScript     

使用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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved