asp.net(c#)開發(fā)中的文件上傳組件uploadify的使用方法(帶進(jìn)度條)
在Web開發(fā)中,有很多可以上傳的組件模塊,利用HTML的File控件的上傳也是一種辦法,不過這種方式,需要處理的細(xì)節(jié)比較多,而且只能支持單文件的操作。在目前Web開發(fā)中用的比較多的,可能uploadify(參考http://www.uploadify.com/)也算一個(gè)吧,不過這個(gè)版本一直在變化,他們的腳本調(diào)用也有很大的不同,甚至調(diào)用及參數(shù)都一直在變化,很早的時(shí)候,那個(gè)Flash的按鈕文字還沒法變化,本篇隨筆主要根據(jù)項(xiàng)目實(shí)際,介紹一下3.1版本的uploadify的控件使用,這版本目前還是最新的,因此對我們做Web開發(fā)來說,有一定的參考性。
這個(gè)控件有很多參數(shù)控制,以及事件的處理響應(yīng),相對來說也比較好用。參數(shù)控制可以控制上傳文件多選、文件類型、文件大小、文件數(shù)量、檢查文件是否存在,以及一些按鈕參數(shù)的控制,如文字、高度、寬度等,對提交文件成功與否、完成操作、取消、停止上傳等等都有控制,他們的幫助文檔也寫得比較完善,不過就是各個(gè)版本的方法參數(shù)完全不同了,但控件是一個(gè)好控件。
控件的使用首先要加入必備的腳本類庫,由于該控件是利用了Jquery的功能,因此還需要應(yīng)用Jquery腳本文件,如下所示。
<script src="http://www.dbjr.com.cn/JQuery/jquery-1.8.0.min.js" type="text/javascript"></script>
<script src="http://www.dbjr.com.cn/JQueryTools/uploadify/jquery.uploadify-3.1.min.js" type="text/javascript"></script>
<link href="http://www.dbjr.com.cn/JQueryTools/uploadify/uploadify.css" rel="stylesheet" type="text/css" />
配置控件的一些參數(shù),以及相應(yīng)的處理事件,如下所示。
<script language="javascript" type="text/javascript">
$(function () {
var guid = '<%=Request["guid"] %>';
var type = '<%=Request["type"] %>';
if (guid == null || guid == "") {
guid = newGuid();
}
if (type != null) {
type = type + '/';
}
            $('#file_upload').uploadify({
                'swf': 'uploadify.swf',                        //FLash文件路徑
                'buttonText': '瀏  覽',                        //按鈕文本
                'uploader': 'uploadhandler.ashx?guid=' + guid, //處理ASHX頁面
                'formData' : { 'folder' : 'picture' },         //傳參數(shù)
                'queueID': 'fileQueue',                        //隊(duì)列的ID
                'queueSizeLimit': 10,                           //隊(duì)列最多可上傳文件數(shù)量,默認(rèn)為999
                'auto': false,                                 //選擇文件后是否自動上傳,默認(rèn)為true
                'multi': true,                                 //是否為多選,默認(rèn)為true
                'removeCompleted': true,                       //是否完成后移除序列,默認(rèn)為true
                'fileSizeLimit': '10MB',                       //單個(gè)文件大小,0為無限制,可接受KB,MB,GB等單位的字符串值
                'fileTypeDesc': 'Image Files',                 //文件描述
                'fileTypeExts': '*.gif; *.jpg; *.png; *.bmp',  //上傳的文件后綴過濾器
                'onQueueComplete': function (event, data) {    //所有隊(duì)列完成后事件
                    //ShowUpFiles(guid, type, show_div);
                    alert("上傳完畢!");
                },
                'onUploadError': function (event, queueId, fileObj, errorObj) {
                    alert(errorObj.type + ":" + errorObj.info);
                }
            });
        });
        function newGuid() {
            var guid = "";
            for (var i = 1; i <= 32; i++){
              var n = Math.floor(Math.random()*16.0).toString(16);
              guid +=   n;
              if((i==8)||(i==12)||(i==16)||(i==20))
                guid += "-";
            }
            return guid;
        }
    </script>
再次提一下,這個(gè)控件不要參考網(wǎng)上其他的一些說明,否則可能參數(shù)及用法不正確,一定要找到對應(yīng)版本的說明(本篇指的是3.1.1),最好參考該版本的在線文檔。
上面的參數(shù),我基本上都給了注釋了,還有一些不是很重要的參數(shù),這里沒有列出來,需要可以參考在線文檔吧。
值得提到的是,這個(gè)版本可以修改Flash里面的文字,非常棒,很討厭以前的那個(gè)默認(rèn)Browse的英文,雖然以前替代圖片可以修改文字,但是還是不太好用。這個(gè)直接修改文字,非常好。
值得注意的是uploader參數(shù),這個(gè)是我們ashx的后臺處理程序,就是控件提交文件給那個(gè)頁面進(jìn)行保存處理,添加數(shù)據(jù)庫記錄等操作。

頁面代碼使用很簡單,如下所示
<body style="margin-left:10px; margin-top:10px">
<form id="form1" runat="server" enctype="multipart/form-data">
<div id="fileQueue" class="fileQueue"></div>
    <div>
    <input type="file" name="file_upload" id="file_upload" />
        <p>
            <input type="button" class="shortbutton" id="btnUpload" onclick="javascript:$('#file_upload').uploadify('upload','*')" value="上傳" />
                
            <input type="button" class="shortbutton" id="btnCancelUpload" onclick="javascript:$('#file_upload').uploadify('cancel')" value="取消" />
        </p>
        <div id="div_show_files"></div>
    </div>
    </form>
</body>
關(guān)鍵是后臺上傳文件的保存操作了,asp.net一般采用ashx的處理頁面來處理。
/// <summary>
/// 文件上傳后臺處理頁面
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class UploadHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Charset = "utf-8";
            try
            {
                string guid = context.Request.QueryString["guid"];
                string folder = context.Request["folder"];
                //LogTextHelper.Info(folder);
                HttpPostedFile file = context.Request.Files["Filedata"];
                if (file != null)
                {                    
                    string oldFileName = file.FileName;//原文件名                    
                    int size = file.ContentLength;//附件大小
                    string extenstion = oldFileName.Substring(oldFileName.LastIndexOf(".") + 1);//后綴名                    
                    string newFileName = GetNewFileName(oldFileName);//生成新文件名
                    //LogTextHelper.Info(newFileName);
                    #region 上傳到遠(yuǎn)程服務(wù)器
                    //FileServerManage fsw = new FileServerManage();
                    //string uploadFilePath = "/" + newFileName;
                    //if (!string.IsNullOrEmpty(folder))
                    //{
                    //    uploadFilePath = string.Format("/{0}/{1}", folder, newFileName);
                    //}
                    //bool uploaded = fsw.UploadFile(file.InputStream, "/" + folder + "/" + newFileName); 
                    #endregion
#region 本地服務(wù)器上傳
                    AppConfig config = new AppConfig();
                    string uploadFiles = config.AppConfigGet("uploadFiles");
                    if (string.IsNullOrEmpty(uploadFiles))
                    {
                        uploadFiles = "uploadFiles";
                    }
                    if (!string.IsNullOrEmpty(folder))
                    {
                        uploadFiles = Path.Combine(uploadFiles, folder);
                    }
                    string uploadPath = Path.Combine(HttpContext.Current.Server.MapPath("/"), uploadFiles);
                    if (!Directory.Exists(uploadPath))
                    {
                        Directory.CreateDirectory(uploadPath);
                    }
                    string newFilePath = Path.Combine(uploadPath, newFileName);
                    LogTextHelper.Info(newFilePath);
                    file.SaveAs(newFilePath);
                    bool uploaded = File.Exists(newFilePath); 
#endregion
                    if (uploaded)
                    {
                        #region 文件保存成功后,寫入附件的數(shù)據(jù)庫記錄
                        //AttachmentInfo attachmentInfo = new AttachmentInfo();
                        //attachmentInfo.EditorTime = DateTime.Now;
                        //attachmentInfo.FileExtend = extenstion;
                        //attachmentInfo.FileName = folader + "/" + newFileName;
                        //attachmentInfo.OldFileName = oldFileName;
                        //attachmentInfo.Size = size;
                        //attachmentInfo.Guid = guid;
                        //BLLFactory<Attachment>.Instance.Insert(attachmentInfo); 
                        #endregion
                    }
                }
                else
                {
                    LogTextHelper.Error("上傳文件失敗");
                }
            }
            catch (Exception ex)
            {
                LogTextHelper.Error("上傳文件失敗", ex);
                throw;
            } 
        }
        /// <summary>
        /// 獲取新的名稱 比如:aa.jpg轉(zhuǎn)化為aa(20090504).jpg
        /// </summary>
        /// <param name="fileName">文件名稱[aa.jpg]</param>
        /// <returns>新的文件名稱</returns>
        public static string GetNewFileName(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
                return string.Empty;
            //文件后綴名
            string extenstion = fileName.Substring(fileName.LastIndexOf(".") + 1);
            string name = fileName.Substring(0, fileName.LastIndexOf(".")) + "(" + DateTime.Now.ToFileTime() + ")";
            string newFileName = name + "." + extenstion;
            return newFileName;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }


- C#使用winform實(shí)現(xiàn)進(jìn)度條效果
 - Winform 實(shí)現(xiàn)進(jìn)度條彈窗和任務(wù)控制
 - C# Winform下載文件并顯示進(jìn)度條的實(shí)現(xiàn)代碼
 - c#進(jìn)度條 progressBar 使用方法的小例子
 - c#根據(jù)文件大小顯示文件復(fù)制進(jìn)度條實(shí)例
 - C#實(shí)現(xiàn)帶百分比的進(jìn)度條功能示例
 - C#中常使用進(jìn)度條的代碼
 - C#實(shí)現(xiàn)炫酷啟動圖-動態(tài)進(jìn)度條效果
 - C#實(shí)現(xiàn)帶進(jìn)度條的ListView
 - C#?Winform實(shí)現(xiàn)進(jìn)度條顯示
 
相關(guān)文章
 通過ASP.net實(shí)現(xiàn)flash對數(shù)據(jù)庫的訪問
近來網(wǎng)站需要在flash中提取數(shù)據(jù)庫中的數(shù)據(jù),從網(wǎng)上找了一點(diǎn)資料,今天下午在自己的機(jī)器上實(shí)現(xiàn)了一下,還是比較簡單的。2009-08-08
 ASP.NET框架中的數(shù)據(jù)綁定概要與數(shù)據(jù)綁定表達(dá)式的使用
數(shù)據(jù)綁定是ASP.NET中操作數(shù)據(jù)的基礎(chǔ)方式,這里我們暫時(shí)拋開.NET提供的控件,來從基礎(chǔ)上講解ASP.NET框架中的數(shù)據(jù)綁定概要與數(shù)據(jù)綁定表達(dá)式的使用:2016-06-06
 為HttpClient添加默認(rèn)請求報(bào)頭的四種解決方案
這篇文章主要給大家介紹了關(guān)于為HttpClient添加默認(rèn)請求報(bào)頭的四種解決方案,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用HttpClient具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
 .NET運(yùn)行界面上,實(shí)現(xiàn)隨意拖動控件的方法
.NET運(yùn)行界面上,實(shí)現(xiàn)隨意拖動控件的方法,需要的朋友可以參考一下2013-03-03

