C#結(jié)合JavaScript實(shí)現(xiàn)多文件上傳功能
需求
在許多應(yīng)用場景里,多文件上傳是一項(xiàng)比較實(shí)用的功能。實(shí)際應(yīng)用中,多文件上傳可以考慮如下需求:
1、對上傳文件的類型、大小有一個基本的控制。
2、上傳文件時有一個進(jìn)度顯示,包括當(dāng)前文件和整體進(jìn)度。
3、上傳后,在服務(wù)端后續(xù)事件進(jìn)行一些處理。
引入
首先請?jiān)赪EB應(yīng)用程序根目錄下創(chuàng)建COMMON目錄,并引入 JavaScript 程序包
下載成功后解壓到COMMON目錄即可,請引入如下圖中的 JS 文件:
另外,我們還需要在 app_data目錄下創(chuàng)建 ajaxUploadFiles 子目錄,以備上傳創(chuàng)建文件使用。
關(guān)鍵代碼
操作界面
界面上放置標(biāo)準(zhǔn)的 input file 控件,并將其服務(wù)器化,即 runat="server"。點(diǎn)擊選擇文件,選中所有目標(biāo)文件后,自動實(shí)現(xiàn)文件上傳功能。
示例界面如下:
?
示例UI代碼如下:
<input class="file" type="file" id="ajaxMfile" runat="server" onbeginupload="ajax_uploadFiles_beginUpload" onprogressupload="ajax_uploadFiles_progressUpload" onendupload="ajax_uploadFiles_endUpload" multiple="multiple" allowtype="pptx|docx|mp3|txt|std" allowsize="500m|100m" fileindex="0" name="fileupload" serverbuttonid="ajaxEndBtn" serverfilelistid="ajaxReturnFileName" progresspanelid="ajaxMfileProgressPanel" onchange="ajax_uploadFiles(this);return false" /> <asp:TextBox runat="server" Width="100%" ID="ajaxReturnFileName" style="display:none" ></asp:TextBox> <br /> <asp:button ID="ajaxEndBtn" text="后臺處理" runat="server" style="display:none" onclick="ajaxEndBtn_Click" /> <br /> <br /> <table style="display:none; color:White" id="ajaxMfileProgressPanel"> <tr> <td > 當(dāng)前文件:</td> <td style="position:relative; padding:0px"> <asp:Label Font-Size="9pt" style="z-index:1;position:absolute;left:0px;top:-9px;" Width="300px" runat="server" ID="ajax_uploadFiles_curfilename"/> </td> </tr> <tr> <td style="position:relative; padding:0px;width:120px"> 當(dāng)前文件進(jìn)度<asp:Label style="z-index:1;position:absolute;left:85px;top:-9px;" runat="server" Font-Size="9pt" ID="ajax_uploadFiles_upprogress"></asp:Label> </td> <td style="position:relative; padding:10px"> <img id="ajax_uploadFiles_curprogress" style="z-index:1;position:absolute;left:0px;top:4px;width:0px;height:12px" alt="" src="/common/Jquery/images/win7progress.jpg" /> <div id="ajax_uploadFiles_curbg" style="z-index:0;position:absolute;left:0px;top:4px;width:300px;height:12px;background-color:Gray"></div> </td> </tr> <tr> <td style="position:relative; padding:0px"> 上傳總量進(jìn)度<asp:Label style="z-index:1;position:absolute;left:85px;top:-9px;" runat="server" Font-Size="9pt" ID="ajax_uploadFiles_cprogress"></asp:Label></td> <td style="position:relative; padding:10px"> <img id="ajax_uploadFiles_totalprogress" style="z-index:1;position:absolute;left:0px;top:4px;width:0px;height:12px" alt="" src="/common/Jquery/images/win7progress2.jpg" /> <div id="ajax_uploadFiles_totalbg" style="z-index:0; position:absolute;left:0px;top:4px;width:300px;height:12px;background-color:Gray"></div> </td> </tr> </table> <table style="color:White; width:100%"> <tr> <td style="position:relative"> <asp:Label runat="server" Font-Size="11pt" ID="ajax_uploadFiles_serverProcessTip"></asp:Label> </td> </tr> </table>
input file 控件的一些設(shè)置如下:
(1)onbeginupload="ajax_uploadFiles_beginUpload" js方法,開始上傳前事件,默認(rèn)值
(2)onprogressupload="ajax_uploadFiles_progressUpload" js方法,上傳中事件,默認(rèn)值
(3)onendupload="ajax_uploadFiles_endUpload" js方法,選擇完文件上傳事件,默認(rèn)值
(4)multiple="multiple" 控件屬性,允許多文件選中上傳
(5)allowtype="pptx|docx|mp3|txt|std" 自定義屬性,允許上傳的文件類型,以 | 分隔
(6)allowsize="500m|100m" 自定義屬性,允許上傳的文件最大尺寸,可以以 | 分隔,并一一對應(yīng),如果不對應(yīng),則根據(jù) allowtype 的設(shè)置從左至右進(jìn)行匹配
如舉例中的設(shè)置則表示為,pptx 允許最大 500M , docx 最大 100M,后面未設(shè)置則均為100M
(7) serverbuttonid="ajaxEndBtn" 自定義屬性,執(zhí)行的服務(wù)器按鈕ID,默認(rèn)值
(8)serverfilelistid="ajaxReturnFileName" 自定義屬性,服務(wù)器端返回的文件ID列表,默認(rèn)值
(9)οnchange="ajax_uploadFiles(this);return false" 自定義屬性,js方法,選擇文件后自動執(zhí)行上傳功能,默認(rèn)值
根據(jù)示例代碼的設(shè)置,以上部分除了 allowtype和 allowsize 均可以不用改變設(shè)置。
上傳中的效果如下圖:
JavaScript包程序
本包程序?qū)崿F(xiàn)了前面設(shè)置的界面元素方法、事件、屬性的實(shí)現(xiàn)及對文件上傳的客戶端控制,示例代碼如下
//批量上傳文件的內(nèi)置默認(rèn)輔助方法,表示每上傳一個文件之前發(fā)生的事件, //事件的fileObj參數(shù)代表 file對象(上傳控件),由主方法自動傳入,開發(fā)者可以重新指定自定義方法 function ajax_uploadFiles_beginUpload(fileObj) { var fIndex = parseInt(fileObj.getAttribute("fileindex"), 10); if (fIndex == 0) { document.getElementById('ajax_uploadFiles_serverProcessTip').innerHTML = ''; document.getElementById("ajax_uploadFiles_upprogress").innerHTML = ""; document.getElementById("ajax_uploadFiles_cprogress").innerHTML = ""; document.getElementById("ajax_uploadFiles_totalprogress").style.width = "0px"; document.getElementById(fileObj.getAttribute("serverfilelistid")).value = ""; } document.getElementById("ajax_uploadFiles_curfilename").innerHTML = fileObj.files[fIndex].name; } //批量上傳文件的內(nèi)置默認(rèn)輔助方法,表示當(dāng)前正在上傳文件時發(fā)生的事件(主要用于顯示上傳進(jìn)度), //事件的fileObj參數(shù)代表 file對象(上傳控件), loaded:已經(jīng)上傳的文件總字節(jié), total:正在上傳的文件總字?jǐn)?shù), // percent:不超過100的整數(shù),表示為百分比。這些參數(shù)由主方法自動傳入,開發(fā)者可以重新指定自定義方法 function ajax_uploadFiles_progressUpload(fileObj, loaded, total, percent) { document.getElementById("ajax_uploadFiles_upprogress").innerHTML = ("" + percent + "%"); var curb = parseInt(document.getElementById("ajax_uploadFiles_curbg").style.width, 10); document.getElementById("ajax_uploadFiles_curprogress").style.width = Math.floor(curb * loaded / total) + "px"; } //批量上傳文件的內(nèi)置默認(rèn)輔助方法,表示當(dāng)前文件上傳完成時發(fā)生的事件(主要用于處理文件上傳后的跟蹤處理,并且返回服務(wù)器上保存的文件列到一個文本框中,以|分隔), //事件的fileObj參數(shù)代表 file對象(上傳控件), type:上傳狀態(tài)返回,包括success成功,error失敗, //data:文件的數(shù)據(jù),暫時未使用, desfile:要保存在服務(wù)器上的文件名 // 這些參數(shù)由主方法自動傳入,開發(fā)者可以重新指定自定義方法 function ajax_uploadFiles_endUpload(fileObj, type, data, desfile) { var fIndex = parseInt(fileObj.getAttribute("fileindex"), 10); var filecount = fileObj.files.length; document.getElementById(fileObj.getAttribute("serverfilelistid")).value += desfile + "|"; var totalb = parseInt(document.getElementById("ajax_uploadFiles_totalbg").style.width, 10); document.getElementById("ajax_uploadFiles_totalprogress").style.width = Math.floor(totalb * (fIndex + 1) / filecount) + "px"; document.getElementById("ajax_uploadFiles_cprogress").innerHTML = ("" + Math.floor(100 * (fIndex + 1) / filecount) + "%"); if (fIndex < filecount - 1) { fIndex++; fileObj.setAttribute("fileindex", fIndex); ajax_uploadFiles(fileObj); return; } fileObj.setAttribute("fileindex", 0); if (type == "success") { document.getElementById('ajaxMfile').style.display='none'; document.getElementById('ajax_uploadFiles_serverProcessTip').innerHTML = '上傳完成!正在進(jìn)行后臺處理...'; document.getElementById(fileObj.getAttribute("serverbuttonid")).click(); } else if (type == "error") { alert("error"); } } //生成一個guid function newguid() { function S4() { return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); } return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4()); } //批量上傳文件的主方法,fileObj參數(shù)代表 file對象(上傳控件) function ajax_uploadFiles(fileObj) { var formData = new FormData(); var fIndex = parseInt(fileObj.getAttribute("fileindex"), 10); var filecount = fileObj.files.length; if (filecount == 0) { alert('請先瀏覽選擇文件...'); return; } var uploadSessionId = newguid(); var upfile = fileObj.files[fIndex].name; var dotpos = upfile.lastIndexOf('.'); var desfile = ""; var exname = ""; if (dotpos > 0) { exname = upfile.substring(dotpos + 1, upfile.length); desfile = uploadSessionId + upfile.substring(0, dotpos) + '.' + exname; } else { desfile = uploadSessionId + upfile; } // alert(Math.round(upsize / 1024)); if (fIndex == 0) { var allowtype = fileObj.getAttribute("allowtype"); var allowsize = fileObj.getAttribute("allowsize"); var at = allowtype.split('|'); var as = allowsize.split('|'); for (var j = 0; j < filecount; j++) { var validfile = fileObj.files[j].name; var upsize = fileObj.files[j].size; var validdotpos = validfile.lastIndexOf('.'); var validexname = ""; if (validdotpos > 0) { validexname = validfile.substring(validdotpos + 1, validfile.length); } var i = 0; if (allowtype != "") { var find = false; for (i = 0; i < at.length; i++) { if (at[i].toLowerCase() == validexname.toLowerCase()) { find = true; break; } } if (find == false) { alert("文件" + validfile + "上傳的類型不符合要求!僅允許上傳擴(kuò)展名為:" + allowtype.split("|").join("、") + "的文件。"); fileObj.style.display = ''; document.getElementById(fileObj.getAttribute("progresspanelid")).style.display = 'none'; var t = fileObj; t.outerHTML = t.outerHTML; return; } } if (allowsize != "") { if (at.length <= as.length) { } else { i = 0; } as[i] = as[i].toLowerCase(); var csize = parseInt(as[i]); var tsize = upsize; if (as[i].lastIndexOf('k') != -1) { csize = csize * 1024; tsize = Math.round(upsize / 1024) + "KB"; } else if (as[i].lastIndexOf('m') != -1) { csize = csize * 1024 * 1024; tsize = Math.round(upsize / 1024 / 1024) + "MB"; } else if (as[i].lastIndexOf('g') != -1) { csize = csize * 1024 * 1024 * 1024; tsize = Math.round(upsize / 1024 / 1024 / 1024) + "GB"; } else if (as[i].lastIndexOf('t') != -1) { csize = csize * 1024 * 1024 * 1024 * 1024; tsize = Math.round(upsize / 1024 / 1024 / 1024 / 1024) + "TB"; } if (upsize > csize) { alert("上傳文件" + validfile + "的大小近" + tsize + ",系統(tǒng)規(guī)定大小不能超過" + as[i].toUpperCase() + ",請重新選擇。"); fileObj.style.display = ''; document.getElementById(fileObj.getAttribute("progresspanelid")).style.display = 'none'; var t = fileObj; t.outerHTML = t.outerHTML; return; } } } //j } // findex // document.getElementById(callObjId).disabled = 'disabled'; // if (beginFuncName != null) { // beginFuncName(fIndex, filecount,upfile); // } fileObj.style.display = 'none'; document.getElementById(fileObj.getAttribute("progresspanelid")).style.display = ''; var findfunc = fileObj.getAttribute("onbeginupload"); if (eval(findfunc)) { var execfunc = eval(findfunc); // alert(findfunc); execfunc(fileObj); } formData.append("file", fileObj.files[fIndex]); //append()里面的第一個參數(shù)file對應(yīng)permission/upload里面的參數(shù)file var processUploadUrl = window.location.protocol + "http://" + window.location.host + "http://common//uploadfile.ashx?guid=" + uploadSessionId; $.ajax({ type: "post", async: true, //這里要設(shè)置異步上傳,才能成功調(diào)用myXhr.upload.addEventListener('progress',function(e){}),progress的回掉函數(shù) Accept: 'text/html;charset=UTF-8', data: formData, contentType: "multipart/form-data", url: processUploadUrl, processData: false, // 告訴jQuery不要去處理發(fā)送的數(shù)據(jù) contentType: false, // 告訴jQuery不要去設(shè)置Content-Type請求頭 xhr: function () { myXhr = $.ajaxSettings.xhr(); if (myXhr.upload) { // check if upload property exists myXhr.upload.addEventListener('progress', function (e) { var loaded = e.loaded; //已經(jīng)上傳大小情況 var total = e.total; //附件總大小 var percent = Math.floor(100 * loaded / total); //已經(jīng)上傳的百分比 // if (progressFuncName != null) { // progressFuncName(loaded, total, percent); // } var findfunc = fileObj.getAttribute("onprogressupload"); if (eval(findfunc)) { var execfunc = eval(findfunc); // alert(findfunc); execfunc(fileObj, loaded, total, percent); } // $("#processBar").css("width", percent); }, false); // for handling the progress of the upload } return myXhr; }, success: function (data) { if (fIndex == fileObj.files.length - 1) { fileObj.style.display = ''; document.getElementById(fileObj.getAttribute("progresspanelid")).style.display = 'none'; var t = fileObj; t.outerHTML = t.outerHTML; } // if (endFuncName != null) { // endFuncName("success", data, desfile, fIndex,filecount); // } var findfunc = fileObj.getAttribute("onendupload"); if (eval(findfunc)) { var execfunc = eval(findfunc); // alert(findfunc); execfunc(fileObj, "success", data, desfile); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert(errorThrown); if (endFuncName != null) { endFuncName(fileObj, "error", null, ''); } } }); }
服務(wù)端 ashx 程序
ashx,一般處理程序(HttpHandler)是·NET眾多web組件的一種。一個 httpHandler 接受并處理一個http請求,類似 Java 中的 servlet 。
本程序?qū)崿F(xiàn)服務(wù)器端上傳文件的接收和另存操作,在這里我們存為uploadfile.ashx,代碼如下:
<%@ WebHandler Language="C#" Class="Handler" %> using System; using System.Web; using System.IO; public class Handler : IHttpHandler { public void ProcessRequest (HttpContext context) { if (context.Request.Files.Count > 0) { //HttpContext.Current.Request.FilePath; string strPath = System.Web.HttpContext.Current.Server.MapPath("~/app_data/ajaxUploadFiles/"); string strName = context.Request.Files[0].FileName; string ext=Path.GetExtension(strName); string filename =HttpContext.Current.Request.QueryString["guid"].ToString()+Path.GetFileNameWithoutExtension(strName); if(ext!=""){ filename = filename + ext; } context.Request.Files[0].SaveAs(System.IO.Path.Combine(strPath, filename)); } } public bool IsReusable { get { return false; } } }
服務(wù)端上傳后處理程序
在多個文件上傳到服務(wù)器后,我們需要對文件進(jìn)行后期處理,在前端我們設(shè)置了ID為 “ajaxEndBtn”的服務(wù)器按鈕,進(jìn)行模擬調(diào)用其 click 事件。
服務(wù)器端按鈕處理事件示例代碼如下:
void ajaxEndBtn_Click(object sender, EventArgs e) { //得到保存后的文件名列表 string[] upfiles = ajaxReturnFileName.Text.Split('|'); //給予用戶基本的提示 ajax_uploadFiles_serverProcessTip.Text = "本次上傳分析:共計(jì)上傳" + (upfiles.Length - 1).ToString() + "個文件。"; //遍歷上傳文件列表,進(jìn)行后期處理 foreach (string filename in upfiles) { if (filename.Trim() == "") continue; string upfilename = Request.PhysicalApplicationPath + "app_data\\ajaxUploadFiles\\" + filename; string exname = System.IO.Path.GetExtension(upfilename); //執(zhí)行業(yè)務(wù)處理程序 }
小結(jié)
本文提供的代碼僅供參考,默認(rèn)的設(shè)置僅可能提供最基礎(chǔ)的實(shí)現(xiàn),比如 ashx 程序還需要進(jìn)行安全控制;進(jìn)度圖片和UI可以重新設(shè)計(jì);實(shí)際的業(yè)務(wù)可以根據(jù)需求對控件的屬性、事件進(jìn)行重寫。
以上就是C#結(jié)合JavaScript實(shí)現(xiàn)多文件上傳功能的詳細(xì)內(nèi)容,更多關(guān)于C#多文件上傳的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#自動類型轉(zhuǎn)換與強(qiáng)制類型轉(zhuǎn)換的講解
今天小編就為大家分享一篇關(guān)于C#自動類型轉(zhuǎn)換與強(qiáng)制類型轉(zhuǎn)換的講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-01-01ItemsControl 數(shù)據(jù)綁定的兩種方式
這篇文章主要介紹了ItemsControl 數(shù)據(jù)綁定的兩種方式,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-03-03c#中string的特性介紹及注意事項(xiàng)小結(jié)
這篇文章主要給大家介紹了關(guān)于c#中string的特性介紹及注意事項(xiàng)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用c#具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11Unity?UGUI的CanvasScaler畫布縮放器組件介紹使用
這篇文章主要為大家介紹了Unity?UGUI的CanvasScaler畫布縮放器組件介紹使用,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07學(xué)習(xí)C#靜態(tài)函數(shù)及變量的一個精典例子與代碼
學(xué)習(xí)C#靜態(tài)函數(shù)及變量的一個精典例子與代碼...2007-03-03C#實(shí)現(xiàn)將網(wǎng)址生成二維碼圖片方法介紹
這篇文章介紹了C#實(shí)現(xiàn)將網(wǎng)址生成二維碼圖片的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-04-04