asp.net文件上傳解決方案(圖片上傳、單文件上傳、多文件上傳、檢查文件類(lèi)型)
小編之前也介紹了許多ASP.NET文件上傳的解決案例,今天來(lái)個(gè)asp.net文件上傳大集合。
1、使用標(biāo)準(zhǔn)HTML來(lái)進(jìn)行圖片上傳
前臺(tái)代碼:
<body> <form id="form1" runat="server"> <div> <table> <tr> <td colspan="2" style="height: 21px" > 使用標(biāo)準(zhǔn)HTML來(lái)進(jìn)行圖片上傳</td> </tr> <tr> <td style="width: 400px"> <input id="InputFile" style="width: 399px" type="file" runat="server" /></td> <td style="width: 80px"> <asp:Button ID="UploadButton" runat="server" Text="上傳圖片" OnClick="UploadButton_Click" /></td> </tr> <tr> <td colspan="2" > <asp:Label ID="Lb_Info" runat="server" ForeColor="Red"></asp:Label></td> </tr> </table> </div> </form> </body>
后臺(tái)代碼:
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void UploadButton_Click(object sender, EventArgs e) { string uploadName = InputFile.Value;//獲取待上傳圖片的完整路徑,包括文件名 //string uploadName = InputFile.PostedFile.FileName; string pictureName = "";//上傳后的圖片名,以當(dāng)前時(shí)間為文件名,確保文件名沒(méi)有重復(fù) if (InputFile.Value != "") { int idx = uploadName.LastIndexOf("."); string suffix = uploadName.Substring(idx);//獲得上傳的圖片的后綴名 pictureName = DateTime.Now.Ticks.ToString() + suffix; } try { if (uploadName != "") { string path = Server.MapPath("~/images/"); InputFile.PostedFile.SaveAs(path + pictureName); } } catch (Exception ex) { Response.Write(ex); } } }
2 單文件上傳
這是最基本的文件上傳,在asp.net1.x中沒(méi)有這個(gè)FileUpload控件,只有html的上傳控件,那時(shí)候要把html控件轉(zhuǎn)化為服務(wù)器控件, 很不好用。其實(shí)所有文件上傳的美麗效果都是從這個(gè)FileUpload控件衍生,第一個(gè)例子雖然簡(jiǎn)單卻是根本。
前臺(tái)代碼:
<body> <form id="form1" runat="server"> <div> <table style="width: 90%"> <tr> <td style="width: 159px" colspan=2> <strong><span style="font-size: 10pt">最簡(jiǎn)單的單文件上傳</span></strong></td> </tr> <tr> <td style="width: 600px"> <asp:FileUpload ID="FileUpload1" runat="server" Width="600px" /></td> <td align=left> <asp:Button ID="FileUpload_Button" runat="server" Text="上傳圖片" OnClick="FileUpload_Button_Click" /></td> </tr> <tr> <td colspan=2> <asp:Label ID="Upload_info" runat="server" ForeColor="Red" Width="767px"></asp:Label></td> </tr> </table> </div> </form> </body>
后臺(tái)代碼:
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void FileUpload_Button_Click(object sender, EventArgs e) { try { if (FileUpload1.PostedFile.FileName == "") //if (FileUpload1.FileName == "") //if (!FileUpload1.HasFile) //獲取一個(gè)值,該值指示 System.Web.UI.WebControls.FileUpload 控件是否包含文件。包含文件,則為 true;否則為 false。 { this.Upload_info.Text = "請(qǐng)選擇上傳文件!"; } else { string filepath = FileUpload1.PostedFile.FileName; //得到的是文件的完整路徑,包括文件名,如:C:\Documents and Settings\Administrator\My Documents\My Pictures\20022775_m.jpg //string filepath = FileUpload1.FileName; //得到上傳的文件名20022775_m.jpg string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);//20022775_m.jpg string serverpath = Server.MapPath("~/images/") + filename;//取得文件在服務(wù)器上保存的位置C:\Inetpub\wwwroot\WebSite1\images\20022775_m.jpg FileUpload1.PostedFile.SaveAs(serverpath);//將上傳的文件另存為 this.Upload_info.Text = "上傳成功!"; } } catch (Exception ex) { this.Upload_info.Text = "上傳發(fā)生錯(cuò)誤!原因是:" + ex.ToString(); } } }
3、多文件上傳
前臺(tái)代碼:
<body> <form id="form1" runat="server"> <div> <table style="width: 343px"> <tr> <td style="width: 100px"> 多文件上傳</td> <td style="width: 100px"> </td> </tr> <tr> <td style="width: 100px"> <asp:FileUpload ID="FileUpload1" runat="server" Width="475px" /> </td> <td style="width: 100px"> </td> </tr> <tr> <td style="width: 100px"> <asp:FileUpload ID="FileUpload2" runat="server" Width="475px" /></td> <td style="width: 100px"> </td> </tr> <tr> <td style="width: 100px"> <asp:FileUpload ID="FileUpload3" runat="server" Width="475px" /></td> <td style="width: 100px"> </td> </tr> <tr> <td style="width: 100px"> <asp:Button ID="bt_upload" runat="server" OnClick="bt_upload_Click" Text="一起上傳" /> <asp:Label ID="lb_info" runat="server" ForeColor="Red" Width="448px"></asp:Label></td> <td style="width: 100px"> </td> </tr> </table> </div> </form> </body>
后臺(tái)代碼:
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void bt_upload_Click(object sender, EventArgs e) { if (FileUpload1.PostedFile.FileName == "" && FileUpload2.PostedFile.FileName == "" && FileUpload3.PostedFile.FileName == "") { this.lb_info.Text = "請(qǐng)選擇文件!"; } else { HttpFileCollection myfiles = Request.Files; for (int i = 0; i < myfiles.Count; i++) { HttpPostedFile mypost = myfiles[i]; try { if (mypost.ContentLength > 0) { string filepath = mypost.FileName;//C:\Documents and Settings\Administrator\My Documents\My Pictures\20022775_m.jpg string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);//20022775_m.jpg string serverpath = Server.MapPath("~/images/") + filename;//C:\Inetpub\wwwroot\WebSite2\images\20022775_m.jpg mypost.SaveAs(serverpath); this.lb_info.Text = "上傳成功!"; } } catch (Exception ex) { this.lb_info.Text = "上傳發(fā)生錯(cuò)誤!原因:" + ex.Message.ToString(); } } } } }
4、客戶(hù)端檢查上傳文件類(lèi)型(以上傳圖片為例)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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>客戶(hù)端檢查上傳文件類(lèi)型</title> <script language="javascript"> function Check_FileType() { var str=document.getElementById("FileUpload1").value; var pos=str.lastIndexOf("."); var lastname=str.substring(pos,str.length); if(lastname.toLowerCase()!=".jpg"&&lastname.toLowerCase()!=".gif") { alert("您上傳的文件類(lèi)型為"+lastname+",圖片必須為.jpg,.gif類(lèi)型"); return false; } else { return true; } } </script> </head> <body> <form id="form1" runat="server"> <div> <table> <tr> <td colspan="2"> 客戶(hù)端檢查上傳文件類(lèi)型</td> </tr> <tr> <td style="width: 444px"> <asp:FileUpload ID="FileUpload1" runat="server" Width="432px" /></td> <td style="width: 80px"> <asp:Button ID="bt_upload" runat="server" Text="上傳圖片" OnClick="bt_upload_Click" OnClientClick="return Check_FileType()" /></td> </tr> <tr> <td colspan="2" style="height: 21px"> <asp:Label ID="lb_info" runat="server" ForeColor="Red" Width="515px"></asp:Label></td> </tr> </table> </div> </form> </body> </html>
注意:點(diǎn)擊上傳時(shí)先觸發(fā)客戶(hù)端事件OnClientClick="return Check_FileType()"
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void bt_upload_Click(object sender, EventArgs e) { try { if (FileUpload1.PostedFile.FileName == "") { this.lb_info.Text = "請(qǐng)選擇文件!"; } else { string filepath = FileUpload1.PostedFile.FileName; //if (!IsAllowedExtension(FileUpload1)) //{ // this.lb_info.Text = "上傳文件格式不正確!"; //} if (IsAllowedExtension(FileUpload1) == true) { string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1); string serverpath = Server.MapPath("~/images/") + filename; FileUpload1.PostedFile.SaveAs(serverpath); this.lb_info.Text = "上傳成功!"; } else { this.lb_info.Text = "請(qǐng)上傳圖片!"; } } } catch (Exception ex) { this.lb_info.Text = "上傳發(fā)生錯(cuò)誤!原因:" + ex.ToString(); } } private static bool IsAllowedExtension(FileUpload upfile) { string strOldFilePath = ""; string strExtension=""; string[] arrExtension ={ ".gif", ".jpg", ".bmp", ".png" }; if (upfile.PostedFile.FileName != string.Empty) { strOldFilePath = upfile.PostedFile.FileName;//獲得文件的完整路徑名 strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));//獲得文件的擴(kuò)展名,如:.jpg for (int i = 0; i < arrExtension.Length; i++) { if (strExtension.Equals(arrExtension[i])) { return true; } } } return false; } }
注意:若去掉客戶(hù)端的腳本和客戶(hù)端事件OnClientClick="return Check_FileType()",在后臺(tái)代碼
改為:
if (!IsAllowedExtension(FileUpload1)) { this.lb_info.Text = "上傳文件格式不正確!"; }
else if (IsAllowedExtension(FileUpload1) == true)
即變成服務(wù)器端檢查上傳文件類(lèi)型。
5、服務(wù)器端檢查上傳文件的類(lèi)型(文件內(nèi)部真正的格式)
<body> <form id="form1" runat="server"> <div> <table> <tr> <td colspan="2"> 服務(wù)器檢查上傳文件類(lèi)型</td> </tr> <tr> <td style="width: 444px"> <asp:FileUpload ID="FileUpload1" runat="server" Width="432px" /></td> <td style="width: 80px"> <asp:Button ID="bt_upload" runat="server" Text="上傳圖片" OnClick="bt_upload_Click" /></td> </tr> <tr> <td colspan="2" style="height: 21px"> <asp:Label ID="lb_info" runat="server" ForeColor="Red" Width="515px"></asp:Label></td> </tr> </table> </div> </form> </body>
后臺(tái)代碼:
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.IO; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void bt_upload_Click(object sender, EventArgs e) { try { if (FileUpload1.PostedFile.FileName == "") { this.lb_info.Text = "請(qǐng)選擇文件!"; } else { string filepath = FileUpload1.PostedFile.FileName; if (IsAllowedExtension(FileUpload1) == true) { string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1); string serverpath = Server.MapPath("images/") + filename; FileUpload1.PostedFile.SaveAs(serverpath); this.lb_info.Text = "上傳成功!"; } else { this.lb_info.Text = "請(qǐng)上傳圖片"; } } } catch (Exception error) { this.lb_info.Text = "上傳發(fā)生錯(cuò)誤!原因:" + error.ToString(); } } private static bool IsAllowedExtension(FileUpload upfile) { FileStream fs = new FileStream(upfile.PostedFile.FileName, FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader(fs); string fileclass = ""; byte buffer; try { buffer = r.ReadByte(); fileclass = buffer.ToString(); buffer = r.ReadByte(); fileclass += buffer.ToString(); } catch { } r.Close(); fs.Close(); if (fileclass == "255216" || fileclass == "7173"||fileclass=="6677"||fileclass=="13780")//說(shuō)明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar { return true; } else { return false; } } }
為大家推薦一個(gè)專(zhuān)題,供大家學(xué)習(xí):《ASP.NET文件上傳匯總》
是不是內(nèi)容很精彩,喜歡的朋友就收藏起來(lái)吧,以后在遇到ASP.NET文件上傳問(wèn)題的時(shí)候能夠有所幫助。
- ASP.NET簡(jiǎn)單好用功能齊全圖片上傳工具類(lèi)(水印、縮略圖、裁剪等)
- ASP.NET實(shí)現(xiàn)上傳圖片并生成縮略圖的方法
- ASP.NET圖片上傳實(shí)例(附源碼)
- asp.net fileupload控件上傳圖片并預(yù)覽圖片
- Asp.Net上傳圖片同時(shí)生成高清晰縮略圖
- asp.net圖片上傳實(shí)例
- ASP.net WebAPI 上傳圖片實(shí)例
- Asp.Net平臺(tái)下的圖片在線(xiàn)裁剪功能的實(shí)現(xiàn)代碼(源碼打包)
- 基于asp.net實(shí)現(xiàn)圖片在線(xiàn)上傳并在線(xiàn)裁剪功能
相關(guān)文章
.Net Core使用Socket與樹(shù)莓派進(jìn)行通信詳解
這篇文章主要為大家詳細(xì)介紹了.Net Core使用Socket與樹(shù)莓派進(jìn)行通信,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-09-09.net實(shí)現(xiàn)webservice簡(jiǎn)單實(shí)例分享
這篇文章主要介紹了.net實(shí)現(xiàn)webservice簡(jiǎn)單實(shí)例,需要的朋友可以參考下2014-04-04Asp.net的GridView控件實(shí)現(xiàn)單元格可編輯方便用戶(hù)使用
考慮到用戶(hù)使用方便,減少?gòu)棾鲰?yè)面,采用點(diǎn)“編輯”按鈕無(wú)需彈出頁(yè)面直接當(dāng)前行的單元格內(nèi)容就能編輯,思路及代碼如下,有此需求的朋友可以參考下,希望對(duì)大家有所幫助2013-08-08在 .NET Framework 2.0 中未處理的異常導(dǎo)致基于 ASP.NET 的應(yīng)用程序意外退出
如果在 Microsoft .NET Framework 2.0 上構(gòu)建的基于 Microsoft ASP.NET 的應(yīng)用程序中引發(fā)未處理的異常,該應(yīng)用程序?qū)?huì)意外退出。如果出現(xiàn)這個(gè)問(wèn)題,不會(huì)在應(yīng)用程序日志中記錄了解此問(wèn)題所必需的異常信息。2009-11-11Ajax異步無(wú)刷新對(duì)局部數(shù)據(jù)更新
Ajax異步無(wú)刷新對(duì)局部數(shù)據(jù)更新的實(shí)例2013-03-03asp.net UpdatePanel實(shí)現(xiàn)無(wú)刷新上傳圖片
UpdatePanel實(shí)現(xiàn)無(wú)刷新上傳圖片實(shí)現(xiàn)代碼,需要的朋友可以參考下。2010-03-03