asp.net結合uploadify實現多附件上傳

來源:互聯網
上載者:User

標籤:post   名稱   web   queue   jquery外掛程式   attr   settings   size   變更   

1、說明

  uploadify是一款優秀jQuery外掛程式,主要功能是批量上傳檔案。大多數同學對多附件上感測到棘手,現將asp.net結合uploadfiy如何?批量上傳附件給大家講解一下,有什麼不對的地方還請大家多多交流溝通,下面把代碼貼出來大家一起交流。

2、組成

  首先說明一下代碼實現所用到的技術,僅供參考:

    開發工具:vs2010

    目標框架:.NET Framework3.5

    Uploadify:uploadify-v3.1

    Jquery:jquery-1.8.1.js

  最後我會將整個Demo上傳,如果同學們的電腦上有開發環境可直接開啟項目解決方案運行。

3、代碼

  Default.aspx(測試頁面)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="FileUpload._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>    <script src="Scripts/jquery-1.8.1.js" type="text/javascript"></script>    <script src="Scripts/uploadify-v3.1/jquery.uploadify-3.1.js" type="text/javascript"></script>    <link href="Scripts/uploadify-v3.1/uploadify.css" rel="stylesheet" type="text/css" />    <script type="text/javascript">        $(function () {            $("#file_upload").uploadify({                "auto": false,                "swf": "Scripts/uploadify-v3.1/uploadify.swf",                "uploader": "App_Handler/Uploadify.ashx?action=upload",                "removeCompleted": false,                "onUploadSuccess": function (file, data, response) {                    alert(‘檔案 ‘ + file.name + ‘ 已經上傳成功,並返回 ‘ + response + ‘ 伺服器狀態 ‘ + data);                }            });        });    </script></head><body>    <form id="form1" runat="server">    <div>        <input type="file" id="file_upload" name="file_upload" />    </div>    <div>        <a href="javascript:$(‘#file_upload‘).uploadify(‘upload‘);">上傳第一個</a>         <a href="javascript:$(‘#file_upload‘).uploadify(‘upload‘,‘*‘);">上傳隊列</a>         <a href="javascript:$(‘#file_upload‘).uploadify(‘cancel‘);">取消第一個</a>        <a href="javascript:$(‘#file_upload‘).uploadify(‘cancel‘, ‘*‘);">取消隊列</a>    </div>    </form></body></html>

  Uploadify.ashx(一般處理常式)

<%@ WebHandler Language="C#" Class="UploadifyUpload" %>using System;using System.Collections;using System.Data;using System.Web;using System.Web.Services;using System.Web.Services.Protocols;using System.Web.SessionState;using System.IO;using System.Collections.Generic;using System.Web.UI.WebControls;using System.Text;public class UploadifyUpload : IHttpHandler, IRequiresSessionState{    public void ProcessRequest(HttpContext context)    {        context.Response.ContentType = "text/plain";        context.Response.Charset = "utf-8";        string action = context.Request["action"];        switch (action)        {            case "upload":                //上傳附件                upload(context);                break;        }        context.Response.End();    }    /// <summary>    /// 上傳附件    /// </summary>    /// <param name="context"></param>    private void upload(HttpContext context)    {        HttpPostedFile postedFile = context.Request.Files["Filedata"];        if (postedFile != null)        {            string fileName, fileExtension;            int fileSize;            fileName = postedFile.FileName;            fileSize = postedFile.ContentLength;            if (fileName != "")            {                fileExtension = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf(‘.‘));                string path =context.Server.MapPath("/")+ "\\App_Attachments\\";//設定檔案的路徑                string fileUrl = path + DateTime.Now.ToString("yyyyMMddHHmmss") + fileExtension;//儲存檔案路徑                if (!Directory.Exists(path)) {                    Directory.CreateDirectory(path);                }                postedFile.SaveAs(fileUrl);//先儲存源檔案                context.Response.Write("上傳成功!");            }            else            {                context.Response.Write("上傳失敗!");            }        }        else        {            context.Response.Write("上傳失敗!");        }    }    public bool IsReusable    {        get        {            return false;        }    }}

  

4、補充

  給大家貼出一些uploadfiy參數的講解,使用方法就是在Default.aspx測試頁面裡面$("#file_upload").uploadify({});方法中配置,不論參數或事件配置要以英文狀態下的逗號結束,最後一個不需要逗號結束。類似於 

 詳細參數如下:

// 所需的參數id: $this.attr(‘id‘), // DOM對象的IDswf: ‘Scripts/jquery-uploadify/uploadify.swf‘, // uploadify.swf 檔案的路徑uploader: ‘App_Handler/Uploadify.ashx‘, // 幕後處理程式的相對路徑auto: false, // 設定為true當選擇檔案後就直接上傳了,為false需要點擊上傳按鈕才上傳,這裡執行doUpload()方法buttonClass: ‘‘, // 按鈕樣式buttonCursor: ‘hand‘, // 滑鼠指標懸停在按鈕上的樣子buttonImage: null, // 瀏覽按鈕的圖片的路徑buttonText: ‘選擇檔案‘, // 瀏覽按鈕的文本checkExisting: false, // 檔案上傳重複性檢查程式,檢查即將上傳的檔案在伺服器端是否已存在,存在返回1,不存在返回0debug: false, // 如果設定為true則表示啟用SWFUpload的偵錯模式fileObjName: ‘Filedata‘, // 檔案上傳對象的名稱,如果命名為’the_files’,PHP程式可以用$_FILES[‘the_files‘]來處理上傳的檔案對象fileSizeLimit: ‘5MB‘, // 上傳檔案的大小限制 ,如果為整數型則表示以KB為單位的大小,如果是字串,則可以使用(B, KB, MB, or GB)為單位,比如’2MB’;如果設定為0則表示無限制fileTypeDesc: ‘支援的格式:‘, // 這個屬性值必須設定fileTypeExts屬性後才有效,用來設定選擇檔案對話方塊中的提示文本,如設定fileTypeDesc為“請選擇rar doc pdf檔案”fileTypeExts: ‘*.*‘, // 設定可以選擇的檔案的類型,格式如:’*.doc;*.pdf;*.rar’ height: 24, // 設定瀏覽按鈕的高度 ,預設值itemTemplate: false, // 用於設定上傳隊列的HTML模版,可以使用以下標籤:instanceID – Uploadify執行個體的ID fileID – 列隊中此檔案的ID,或者理解為此任務的ID fileName – 檔案的名稱 fileSize – 當前上傳檔案的大小 插入模版標籤時使用格式如:${fileName}method: ‘post‘, // 提交方式Post或Getmulti: true, // 設定為true時可以上傳多個檔案formData: { ‘action‘: ‘upload‘ }, // AnJSON格式上傳每個檔案的同時提交到伺服器的額外資料,可在’onUploadStart’事件中使用’settings’方法動態設定preventCaching: true, // 如果為true,則每次上傳檔案時自動加上一串隨機字串參數,防止URL緩衝影響上傳結果progressData: ‘percentage‘, // 設定上傳進度顯示方式,percentage顯示上傳百分比,speed顯示上傳速度listID: false, // 設定附件列表容器DOM元素的IDqueueID: false, // 設定上傳隊列容器DOM元素的ID,如果為false則自動產生一個隊列容器queueSizeLimit: 999, // 隊列最多顯示的任務數量,如果選擇的檔案數量超出此限制,將會出發onSelectError事件。注意此項並非最大檔案上傳數量,如果要限制最大上傳檔案數量,應設定uploadLimitremoveCompleted: false, // 是否自動將已完成任務從隊列中刪除,如果設定為ture則會從隊列中移除removeTimeout: 3, // 如果設定了任務完成後自動從隊列中移除,則可以規定從完成到被移除的時間間隔requeueErrors: false, // 如果設定為true,則單個任務上傳失敗後將返回錯誤,並重新加入任務隊列上傳successTimeout: 30, // 檔案上傳成功後服務端應返回成功標誌,此項設定返回結果的逾時時間uploadLimit: 0, // 最大上傳檔案數量,如果達到或超出此限制將會觸發onUploadError事件width: 75, // 設定檔案瀏覽按鈕的寬度設定的事件:onDialogClose : function(swfuploadifyQueue) {//當檔案選擇對話方塊關閉時觸發  if( swfuploadifyQueue.filesErrored > 0 ){  alert( ‘添加至隊列時有‘  +swfuploadifyQueue.filesErrored  +‘個檔案發生錯誤n‘  +‘錯誤資訊:‘  +swfuploadifyQueue.errorMsg  +‘n選定的檔案數:‘  +swfuploadifyQueue.filesSelected  +‘n成功添加至隊列的檔案數:‘  +swfuploadifyQueue.filesQueued  +‘n隊列中的總檔案數量:‘  +swfuploadifyQueue.queueLength);  }}onDialogOpen : function() {//當選擇檔案對話方塊開啟時觸發  alert( ‘Open!‘);} onSelect : function(file) {//當每個檔案添加至隊列後觸發  alert( ‘id: ‘ + file.id  + ‘ - 索引: ‘ + file.index  + ‘ - 檔案名稱: ‘ + file.name  + ‘ - 檔案大小: ‘ + file.size  + ‘ - 類型: ‘ + file.type  + ‘ - 建立日期: ‘ + file.creationdate  + ‘ - 修改日期: ‘ + file.modificationdate  + ‘ - 檔案狀態: ‘ + file.filestatus);} onSelectError : function(file,errorCode,errorMsg) {//當檔案選定發生錯誤時觸發  alert( ‘id: ‘ + file.id  + ‘ - 索引: ‘ + file.index  + ‘ - 檔案名稱: ‘ + file.name  + ‘ - 檔案大小: ‘ + file.size  + ‘ - 類型: ‘ + file.type  + ‘ - 建立日期: ‘ + file.creationdate  + ‘ - 修改日期: ‘ + file.modificationdate  + ‘ - 檔案狀態: ‘ + file.filestatus  + ‘ - 錯誤碼: ‘ + errorCode  + ‘ - 錯誤資訊: ‘ + errorMsg);} onQueueComplete : function(stats) {//當隊列中的所有檔案全部完成上傳時觸發  alert( ‘成功上傳的檔案數: ‘ + stats.successful_uploads  + ‘ - 上傳出錯的檔案數: ‘ + stats.upload_errors  + ‘ - 取消上傳的檔案數: ‘ + stats.upload_cancelled  + ‘ - 出錯的檔案數‘ + stats.queue_errors);} onUploadComplete : function(file,swfuploadifyQueue) {//隊列中的每個檔案上傳完成時觸發一次  alert( ‘id: ‘ + file.id  + ‘ - 索引: ‘ + file.index  + ‘ - 檔案名稱: ‘ + file.name  + ‘ - 檔案大小: ‘ + file.size  + ‘ - 類型: ‘ + file.type  + ‘ - 建立日期: ‘ + file.creationdate  + ‘ - 修改日期: ‘ + file.modificationdate  + ‘ - 檔案狀態: ‘ + file.filestatus  + ‘ - 出錯的檔案數: ‘ + swfuploadifyQueue.filesErrored  + ‘ - 錯誤資訊: ‘ + swfuploadifyQueue.errorMsg  + ‘ - 要添加至隊列的數量: ‘ + swfuploadifyQueue.filesSelected  + ‘ - 添加至對立的數量: ‘ + swfuploadifyQueue.filesQueued  + ‘ - 隊列長度: ‘ + swfuploadifyQueue.queueLength);} onUploadError : function(file,errorCode,errorMsg,errorString,swfuploadifyQueue) {//上傳檔案出錯是觸發(每個出錯檔案觸發一次)  alert( ‘id: ‘ + file.id  + ‘ - 索引: ‘ + file.index  + ‘ - 檔案名稱: ‘ + file.name  + ‘ - 檔案大小: ‘ + file.size  + ‘ - 類型: ‘ + file.type  + ‘ - 建立日期: ‘ + file.creationdate  + ‘ - 修改日期: ‘ + file.modificationdate  + ‘ - 檔案狀態: ‘ + file.filestatus  + ‘ - 錯誤碼: ‘ + errorCode  + ‘ - 錯誤描述: ‘ + errorMsg  + ‘ - 簡要錯誤描述: ‘ + errorString  + ‘ - 出錯的檔案數: ‘ + swfuploadifyQueue.filesErrored  + ‘ - 錯誤資訊: ‘ + swfuploadifyQueue.errorMsg  + ‘ - 要添加至隊列的數量: ‘ + swfuploadifyQueue.filesSelected  + ‘ - 添加至對立的數量: ‘ + swfuploadifyQueue.filesQueued  + ‘ - 隊列長度: ‘ + swfuploadifyQueue.queueLength);} onUploadProgress : function(file,fileBytesLoaded,fileTotalBytes,queueBytesLoaded,swfuploadifyQueueUploadSize) {//上傳進度發生變更時觸發alert( ‘id: ‘ + file.id  + ‘ - 索引: ‘ + file.index  + ‘ - 檔案名稱: ‘ + file.name  + ‘ - 檔案大小: ‘ + file.size  + ‘ - 類型: ‘ + file.type  + ‘ - 建立日期: ‘ + file.creationdate  + ‘ - 修改日期: ‘ + file.modificationdate  + ‘ - 檔案狀態: ‘ + file.filestatus  + ‘ - 當前檔案已上傳: ‘ + fileBytesLoaded  + ‘ - 當前檔案大小: ‘ + fileTotalBytes  + ‘ - 隊列已上傳: ‘ + queueBytesLoaded  + ‘ - 隊列大小: ‘ + swfuploadifyQueueUploadSize);} onUploadStart: function(file) {//上傳開始時觸發(每個檔案觸發一次)  alert( ‘id: ‘ + file.id  + ‘ - 索引: ‘ + file.index  + ‘ - 檔案名稱: ‘ + file.name  + ‘ - 檔案大小: ‘ + file.size  + ‘ - 類型: ‘ + file.type  + ‘ - 建立日期: ‘ + file.creationdate  + ‘ - 修改日期: ‘ + file.modificationdate  + ‘ - 檔案狀態: ‘ + file.filestatus );}onUploadSuccess : function(file,data,response) {//上傳完成時觸發(每個檔案觸發一次)  alert( ‘id: ‘ + file.id  + ‘ - 索引: ‘ + file.index  + ‘ - 檔案名稱: ‘ + file.name  + ‘ - 檔案大小: ‘ + file.size  + ‘ - 類型: ‘ + file.type  + ‘ - 建立日期: ‘ + file.creationdate  + ‘ - 修改日期: ‘ + file.modificationdate  + ‘ - 檔案狀態: ‘ + file.filestatus  + ‘ - 伺服器端訊息: ‘ + data  + ‘ - 是否上傳成功: ‘ + response);} 

  

 5、最後奉上Demo

  FileUpload

asp.net結合uploadify實現多附件上傳

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.