天天看點

jQuery上傳插件Uploadify 3.2在.NET下的詳細例子

項目中要使用Uploadify 3.2來實作圖檔上傳并生成縮略通的功能,特此記下來,以供各位參考!

Uploadify下載下傳位址:http://www.uploadify.com/download/

下載下傳下來解壓後估計裡面很多檔案,其實有用的也就jquery.uploadify.min.js、uploadify.css、uploadify.swf和uploadify-cancel.png這四個檔案。你還得下載下傳jQuery庫,我這裡用的是jquery-1.7.2.min.js,另外和大多數JQ插件一樣,同時也需要swfobject.js這個插件,我的是2.2的版本,東西都準備好了,那下面就開始。

前端界面:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="jqUploadify._Default" %>

<!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>
    <link href="scripts/uploadify.css" rel="stylesheet" type="text/css" />
    <link href="scripts/default.css" rel="stylesheet" type="text/css" />

    <script src="scripts/jquery-1.7.2.min.js" type="text/javascript"></script>

    <script src="scripts/swfobject.js" type="text/javascript"></script>

    <script src="scripts/jquery.uploadify.min.js" type="text/javascript"></script>

    <script type="text/javascript">
    $(function(){
        $("#file_upload").uploadify({
            //開啟調試
            'debug' : false,
            //是否自動上傳
            'auto':false,
            'buttonText':'選擇照片',
            //flash
            'swf': "scripts/uploadify.swf",
            //檔案選擇後的容器ID
            'queueID':'uploadfileQueue',
            'uploader':'scripts/upload.ashx',
            'width':'75',
            'height':'24',
            'multi':false,
            'fileTypeDesc':'支援的格式:',
            'fileTypeExts':'*.jpg;*.jpge;*.gif;*.png',
            'fileSizeLimit':'1MB',
            'removeTimeout':1,

            //傳回一個錯誤,選擇檔案的時候觸發
            'onSelectError':function(file, errorCode, errorMsg){
                switch(errorCode) {
                    case -100:
                        alert("上傳的檔案數量已經超出系統限制的"+$('#file_upload').uploadify('settings','queueSizeLimit')+"個檔案!");
                        break;
                    case -110:
                        alert("檔案 ["+file.name+"] 大小超出系統限制的"+$('#file_upload').uploadify('settings','fileSizeLimit')+"大小!");
                        break;
                    case -120:
                        alert("檔案 ["+file.name+"] 大小異常!");
                        break;
                    case -130:
                        alert("檔案 ["+file.name+"] 類型不正确!");
                        break;
                }
            },
            //檢測FLASH失敗調用
            'onFallback':function(){
                alert("您未安裝FLASH控件,無法上傳圖檔!請安裝FLASH控件後再試。");
            },
            //上傳到伺服器,伺服器傳回相應資訊到data裡
            'onUploadSuccess':function(file, data, response){
                //alert(data);
            }
        });
    });

    function doUplaod(){
        $('#file_upload').uploadify('upload','*');
    }

    function closeLoad(){
        $('#file_upload').uploadify('cancel','*');
    }


    </script>

</head>
<body>
    <table width="704" border="0" align="center" cellpadding="0" cellspacing="0" id="__01">
        <tr>
            <td align="center" valign="middle">
                <div id="uploadfileQueue" style="padding: 3px;">
                </div>
                <div id="file_upload">
                </div>
            </td>
        </tr>
        <tr>
            <td height="50" align="center" valign="middle">
                <img alt="" src="images/BeginUpload.gif" width="77" height="23" onclick="doUplaod()" style="cursor: hand" />
                <img alt="" src="images/CancelUpload.gif" width="77" height="23" onclick="closeLoad()" style="cursor: hand" />
            </td>
        </tr>
    </table>
</body>
</html>      

後端的Handler:

using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Web.SessionState;
using System.IO;

namespace jqUploadify.scripts
{
    /// <summary>
    /// $codebehindclassname$ 的摘要說明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class upload : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Charset = "utf-8";

            HttpPostedFile file = context.Request.Files["Filedata"];
            string uploadPath = context.Server.MapPath("..\\uploads\\");

            if (file != null)
            {
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }
                file.SaveAs(uploadPath + file.FileName);
                //生成縮略圖
                MakeThumbnail(uploadPath + file.FileName, uploadPath + "\\s\\" + file.FileName, 80, 80);
            }
        }

        private void MakeThumbnail(string sourcePath, string newPath, int width, int height)
        {
            System.Drawing.Image ig = System.Drawing.Image.FromFile(sourcePath);
            int towidth = width;
            int toheight = height;
            int x = 0;
            int y = 0;
            int ow = ig.Width;
            int oh = ig.Height;
            if ((double)ig.Width / (double)ig.Height > (double)towidth / (double)toheight)
            {
                oh = ig.Height;
                ow = ig.Height * towidth / toheight;
                y = 0;
                x = (ig.Width - ow) / 2;

            }
            else
            {
                ow = ig.Width;
                oh = ig.Width * height / towidth;
                x = 0;
                y = (ig.Height - oh) / 2;
            }
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.Clear(System.Drawing.Color.Transparent);
            g.DrawImage(ig, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);
            try
            {
                bitmap.Save(newPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ig.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}      

這樣我們就是實作圖檔上傳至uploads,生成的縮略圖(這裡設為80*80)存放在uploads下面的s檔案夾中,是不是很簡單呢!當然實際使用過程你還可能碰到一下的問題:

1、在火狐下session出現丢失的情況​​​​

2、IE9出現了按鈕不能點選的問題,可以參考這裡:​​http://www.uploadify.com/forum/#/discussion/9155/uploadify-version-3-2-does-not-work-in-ie9/p1​​

最後貼一個Uploadify參數說明:

Uploadify Version 3.2

Options選項設定

auto    選擇檔案後自動上傳

buttonClass    給“浏覽按鈕”加css的class樣式

buttonCursor    滑鼠移上去形狀:arrow箭頭、hand手型(預設)

buttonImage    滑鼠移上去變換圖檔

buttonText    按鈕文字

checkExisting    在目錄中檢查檔案是否已上傳成功(1 ture,0 false)

debug        是否顯示調試框(預設不顯示false)

fileObjName    設定一個名字,在伺服器處理程式中根據該名字來取上傳檔案的資料。預設為Filedata,$tempFile = $_FILES['Filedata']['tmp_name']

fileSizeLimit    設定允許上傳檔案最大值B, KB, MB, GB 比如:'fileSizeLimit' : '20MB'

fileTypeDesc    選擇的檔案的描述。這個字元串出現在浏覽檔案對話框中檔案類型下拉框處。預設:All Files

fileTypeExts    允許上傳的檔案類型。格式:'fileTypeExts' : '*.gif; *.jpg; *.png'

formData    附帶值,需要通過get or post傳遞的額外資料,需要結合onUploadStart事件一起使用

height        “浏覽按鈕”高度px

itemTemplate    <itemTemplate>節點表示顯示的内容。這些内容中也可以包含綁定到控件DataSource屬性中元素集合的資料。

method        上傳方式。預設:post

multi        選擇檔案時是否可以【選擇多個】。預設:可以true

overrideEvents    不執行預設的onSelect事件

preventCaching    随機緩存值 預設true ,可選true和false.如果選true,那麼在上傳時會加入一個随機數來使每次的URL都不同,以防止緩存.但是可能與正常URL産生沖突

progressData    進度條上顯示的進度:有百分比percentage和速度speed。預設百分比

queueID        給“進度條”加背景css的ID樣式。檔案選擇後的容器ID

queueSizeLimit    允許多檔案上傳的數量。預設:999

removeCompleted    上傳完成後隊列是否自動消失。預設:true

removeTimeout    上傳完成後隊列多長時間後消失。預設 3秒    需要:'removeCompleted' : true,時使用

requeueErrors    隊列上傳出錯,是否繼續復原隊列,即反複嘗試上傳。預設:false

successTimeout    上傳逾時時間。檔案上傳完成後,等待伺服器傳回資訊的時間(秒).超過時間沒有傳回的話,插件認為傳回了成功。 預設:30秒

swf        swf檔案的路徑,本檔案是插件自帶的,不可用其它的代替.本參數不可省略

uploader    上傳處理程式URL,本參數不可省略

uploadLimit    限制總上傳檔案數,預設是999。指同一時間,如果關閉浏覽器後重新打開又可上傳。

width        “浏覽按鈕”寬度px

Events 事件

onCancel    當取消一個上傳隊列中的檔案時觸發,删除時觸發

onClearQueue    清除隊列。當'cancel'方法帶着*參數時,也就是說一次全部取消的時候觸發.queueItemCount是被取消的檔案個數(另外的按鈕)

onDestroy    取消所有的上傳隊列(另外的按鈕)

onDialogClose    當選擇檔案對話框關閉時觸發,不論是點的'确定'還是'取消'都會觸發.如果本事件被添加進了'overrideEvents'參數中,那麼如果在選擇檔案時産生了錯誤,不會有錯誤提示框彈出

onDialogOpen    當選擇檔案框被打開時觸發,沒有傳過來的參數

onDisable    關閉上傳

onEnable    開啟上傳

onFallback    檢測FLASH失敗調用

onInit        每次初始化一個隊列時觸發

onQueueComplete    當隊列中的所有檔案上傳完成時觸發

onSelect    當檔案從浏覽框被添加到隊列中時觸發

onSelectError    選擇檔案出錯時觸發

onSWFReady    flash準備好時觸發

onUploadComplete當一個檔案上傳完成時觸發

onUploadError    當檔案上傳完成但是傳回錯誤時觸發

onUploadProgress上傳彙總

onUploadStart    一個檔案上傳之間觸發

onUploadSuccess    每個上傳完成并成功的檔案都會觸發本事件

Methods 方法

cancel        取消一個上傳隊列

destroy        取消所有上傳隊列

disable        禁止點選“浏覽按鈕”

settings    傳回或修改一個 uploadify執行個體的settings值

stop        停止目前的上傳并重新添加到隊列中去

upload        上傳指定的檔案或者所有隊列中的檔案

​​

jQuery上傳插件Uploadify 3.2在.NET下的詳細例子

繼續閱讀