基於uploadify.js實現多檔案上傳和上傳進度條的顯示

雲霏霏發表於2014-12-08

  uploadify是JQuery的一個外掛,主要實現檔案的非同步上傳功能,可以自定義檔案大小限制、檔案型別、是否自動上傳等屬性,可以顯示上傳的進度條。官網地址是http://www.uploadify.com/,進入官網首頁(不截圖了,其實也沒啥看的),可以看到uploadify的標語"Upload files like magic",意思是說使用uploadify上傳檔案如魔法一般。目前一共分為兩個版本,Flash版和HTML5版,不過HTML5版是收費的,如圖:

這裡我們下載Flash版~~ 

 

 一、簡單檔案上傳的實現

 下載完成後,解壓到當前目錄,可以看到如下目錄:

uploadify.js是基於JQuery的,所以我們也要引入JQuery,紅色圈住的使我們要使用的檔案,額!JQuery是我下載放進去的,大家自己下載一個吧。

新建一個Web專案,然後把上面的檔案都放到專案根目錄下(這樣做不好,大家自己規劃目錄,我就不廢話了),然後新建頁面,引入JQuery、uploadify.js和uploadify.css,接下來該幹些什麼呢?沒有頭緒啊,開啟剛剛的下載目錄看看,有個index.php,開啟看到是一個官方的Demo,那麼就從這個Demo說起吧,下來看看問什麼包裡面沒有JQuery,看圖:

我們可以看到Demo中載入的是googleapis的JQuery,版本是1.7.1,然後看下面的程式碼:

一個form表單,裡面有個input,type是file,下面來看看JS程式碼:

很簡單,用JQuery呼叫了uploadify方法。其中swf和uploader指的是flash檔案的地址和上傳的處理程式。好,下面親自動手來寫一個試試。

既然是檔案上傳,我們要先有一個檔案上傳方法吧,新建FileUpload.ashx檔案,寫入以下程式碼:

 context.Response.ContentType = "text/plain";
        if (context.Request.Files.Count > 0)
        {
            HttpPostedFile file = context.Request.Files[0];
            string ext = System.IO.Path.GetExtension(file.FileName);
            string fileName = DateTime.Now.Ticks + ext;
            string p = "/upload/" + fileName;
            string path = context.Server.MapPath("~/upload/" + fileName);
            file.SaveAs(path);
            context.Response.Write("1");
        }

一個簡單的檔案上傳,有人會問檔案上傳成功問什麼返回“1”呢?我們來看看Uploadify.php,如圖:

這下清楚了吧~還有要記得我們上傳的目錄是upload目錄,記得在專案中新增則個目錄。接下來我們開始寫JS,實現檔案的上傳,模仿官方的Demo,程式碼如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Jsonp.WebForm1" %>

<!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 runat="server">
   <title></title>
   <script src="jquery-1.11.1.min.js"></script>
    <script src="jquery.uploadify.js"></script>
    <link href="uploadify.css" rel="stylesheet" type="text/css" />
</head>

<body>
   <input id="file_upload" name="file_upload" type="file" multiple="true">
</body>
</html>
<script type="text/javascript">
   $(function () {
      $("#file_upload").uploadify({
         height: 30,
         swf: 'uploadify.swf',
         uploader: 'UploadFile.ashx',
         width: 120
      });
   });

</script>

我們就是修改了uploader為我們自己的上傳處理程式,然後F5執行,看看效果:

我們可以看到頁面上面出現了一個按鈕,點選可以開啟對話方塊選中檔案,選擇一個檔案,點選確定,看到檔案上傳成功了:

真的上傳成功了嗎?我們進入upload目錄看看,確實上傳成功了。是不是感覺很神奇?當然,我們也可以同時選則多張圖片,批量上傳,上傳成功後,那個進度條過一段時間會一個一個自動消失。是不是突然發現檔案上傳竟然可以這麼簡單~~

 

 二、自定義Uploadify

   檔案上傳是實現了,但是按鈕樣式和文字都不是我們想要的?下面我們來看一下如何自定義Uploadify外掛,我們開啟jquery.uploadify.js來看一下他的原始碼:

 

開頭的一段密密麻麻的程式碼是用來顯示flash的,不用管她。向下走,我們看到如上圖的程式碼,width、height、swf、uploader,沒錯這個就是他的自定義選項,下面是我總結的這些自定義選項的含義:

    id       : $this.attr('id'), // The ID of the DOM object
    swf      : 'uploadify.swf',  // uploadify flash檔案的路徑
    uploader : 'UploadFile.ashx',  // 上傳檔案的提交地址
    
    // Options
    auto            : true,               // 是否自動上傳檔案
    buttonClass     : '',                 // 按鈕的樣式,這裡可以自定css樣式
    buttonCursor    : 'hand',             // 按鈕滑鼠樣式
    buttonImage     : null,               // 按鈕圖片
    buttonText      : 'SELECT FILES',     // 按鈕顯示的文字
    checkExisting   : false,              // 上傳前是否先檢查檔案是否存在
    debug           : false,              // 是否啟動除錯
    fileObjName     : 'Filedata',         // The name of the file object to use in your server-side script
    fileSizeLimit   : 0,                  // 檔案大小限制,格式為1KB或1MB
    fileTypeDesc    : 'All Files',        // 檔案型別描述
    fileTypeExts    : '*.*',              // 副檔名過濾
    height          : 30,                 // 按鈕高度
    itemTemplate    : false,              // The template for the file item in the queue
    method          : 'post',             // 提交方式
    multi           : true,               // 是否允許多檔案上傳
    formData        : {},                 // An object with additional data to send to the server-side upload script with every file upload
    preventCaching  : true,               // Adds a random value to the Flash URL to prevent caching of it (conflicts with existing parameters)
    progressData    : 'percentage',       // 進度條顯示,百分比
    queueID         : false,              // The ID of the DOM object to use as a file queue (without the #)
    queueSizeLimit  : 999,                // 檔案上傳佇列的大小限制
    removeCompleted : true,               // 上傳成功後移除進度條
    removeTimeout   : 3,                  // The delay in seconds before removing a queue item if removeCompleted is set to true
    requeueErrors   : false,              // Keep errored files in the queue and keep trying to upload them
    successTimeout  : 30,                 // The number of seconds to wait for Flash to detect the server's response after the file has finished uploading
    uploadLimit     : 0,                  // 可以上傳檔案的最大數量
    width           : 120,                // 按鈕寬度
    
    // 這裡是一些擴充套件的事件
    overrideEvents  : []             // (Array) A list of default event handlers to skip
    /*
    onCancel         // Triggered when a file is cancelled from the queue
    onClearQueue     // Triggered during the 'clear queue' method
    onDestroy        // Triggered when the uploadify object is destroyed
    onDialogClose    // Triggered when the browse dialog is closed
    onDialogOpen     // Triggered when the browse dialog is opened
    onDisable        // Triggered when the browse button gets disabled
    onEnable         // Triggered when the browse button gets enabled
    onFallback       // Triggered is Flash is not detected    
    onInit           // Triggered when Uploadify is initialized
    onQueueComplete  // Triggered when all files in the queue have been uploaded
    onSelectError    // Triggered when an error occurs while selecting a file (file size, queue size limit, etc.)
    onSelect         // Triggered for each file that is selected
    onSWFReady       // Triggered when the SWF button is loaded
    onUploadComplete // Triggered when a file upload completes (success or error)
    onUploadError    // Triggered when a file upload returns an error
    onUploadSuccess  // Triggered when a file is uploaded successfully
    onUploadProgress // Triggered every time a file progress is updated
    onUploadStart    // Triggered immediately before a file upload starts

下面我們來寫一個總和示例:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Jsonp.WebForm1" %>

<!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 runat="server">
   <title></title>
   <script src="jquery-1.11.1.min.js"></script>
    <script src="jquery.uploadify.min.js"></script>
    <link href="uploadify.css" rel="stylesheet" type="text/css" />
</head>

<body>
   <input id="file_upload" name="file_upload" type="file" multiple="true">
   <input type="button" value="上傳" onclick="javascript:$('#file_upload').uploadify('upload','*')" />
   <div id="imgBox" style=" overflow:hidden; width:200px; height:200px; "></div>
</body>
</html>
<script type="text/javascript">

   $(function () {
      $("#file_upload").uploadify({
         auto: false,
         fileTypeDesc: 'Image Files',
         fileTypeExts: '*.jpg; *.png;*.gif;*.*',
         height: 30,
         buttonText: '請選擇圖片...',
         swf: 'uploadify.swf',
         uploader: 'UploadFile.ashx',
         width: 120,
         fileSizeLimit: '4MB',
         onUploadSuccess: function (file, data, response) {
            $("#imgBox").html(data);
         },
         onUploadError: function (file, errorCode, errorMsg, errorString) {
            alert('The file ' + file.name + ' could not be uploaded: ' + errorString);
         }
      });
   });
</script>

功能就是上傳圖片,上傳成功後,顯示上傳的圖片。注意這裡自動上傳為false,也就是說不自動上傳圖片,我們給按鈕新增了click事件,來實現手動上傳,程式碼如下:

$('#file_upload').uploadify('upload','*')

注意uploadify後面的引數,'*',這個引數代表上傳所有檔案,如果沒有這個引數的話,只會上傳第一張圖片。

 這個時候,上傳檔案的處理方法如下:

context.Response.ContentType = "text/plain";
        if (context.Request.Files.Count > 0)
        {
            HttpPostedFile file = context.Request.Files[0];
            string ext = System.IO.Path.GetExtension(file.FileName);
            string fileName = DateTime.Now.Ticks + ext;
            string p = "/upload/" + fileName;
            string path = context.Server.MapPath("~/upload/" + fileName);
            file.SaveAs(path);
            context.Response.Write("<img width=\"100px\" height=\"100px\" src=\"" + p + "\" />");
        }
        else
        {
            context.Response.Write("上傳錯誤!");
        }

  

 作者:雲霏霏

QQ交流群:243633526

 部落格地址:http://www.cnblogs.com/yunfeifei/

 宣告:本部落格原創文字只代表本人工作中在某一時間內總結的觀點或結論,與本人所在單位沒有直接利益關係。非商業,未授權,貼子請以現狀保留,轉載時必須保留此段宣告,且在文章頁面明顯位置給出原文連線。

如果大家感覺我的博文對大家有幫助,請推薦支援一把,給我寫作的動力。

 

相關文章