主頁 > 知識庫 > asp.net文件上傳示例分享

asp.net文件上傳示例分享

熱門標(biāo)簽:網(wǎng)站排名優(yōu)化 電銷業(yè)務(wù) 客戶服務(wù) 百度AI接口 國美全國運(yùn)營中心 科大訊飛語音識別系統(tǒng) 人工智能 電商新玩法

方法一:用Web控件FileUpload,上傳到網(wǎng)站根目錄。

Test.aspx關(guān)鍵代碼:

復(fù)制代碼 代碼如下:

form id="form1" runat="server">
asp:FileUpload ID="FileUpload1" runat="server" />
asp:Button ID="Button1" runat="server" Text="上傳" OnClick="Button1_Click" />
asp:Label ID="Label1" runat="server" Text="" Style="color: Red">/asp:Label>
/form>

Test.aspx.cs關(guān)鍵代碼:

復(fù)制代碼 代碼如下:

protected void Button1_Click(object sender, EventArgs e)
{
    if (FileUpload1.HasFile)
    {
    FileUpload1.SaveAs(Server.MapPath("~/") + FileUpload1.FileName);
    Label1.Text = "上傳成功!";
    }
}

方法二:用Html控件HtmlInputFile,上傳到網(wǎng)站根目錄。

Test.aspx關(guān)鍵代碼:
 

復(fù)制代碼 代碼如下:

form id="form1" runat="server">
input type="file" id="file1" runat="server" />
asp:Button ID="Button1" runat="server" Text="上傳" OnClick="Button1_Click" />
asp:Label ID="Label1" runat="server" Text="" Style="color: Red">/asp:Label>
/form>

Test.aspx.cs關(guān)鍵代碼:

復(fù)制代碼 代碼如下:

protected void Button1_Click(object sender, EventArgs e)
{
    if (file1.PostedFile.ContentLength > 0)
    {
    file1.PostedFile.SaveAs(Server.MapPath("~/") + Path.GetFileName(file1.PostedFile.FileName));
    Label1.Text = "上傳成功!";
    }
}

方法三:用Html元素input type="file" …/>,通過Request.Files上傳到網(wǎng)站根目錄。

Test.aspx關(guān)鍵代碼:

復(fù)制代碼 代碼如下:

form id="form1" runat="server" enctype="multipart/form-data">
input type="file" name="file" />
asp:Button ID="Button1" runat="server" Text="上傳" OnClick="Button1_Click" />
asp:Label ID="Label1" runat="server" Text="" Style="color: Red">/asp:Label>
/form>

Test.aspx.cs關(guān)鍵代碼:
 

復(fù)制代碼 代碼如下:

protected void Button1_Click(object sender, EventArgs e)
{
    if (Request.Files["file"].ContentLength > 0)
    {
    Request.Files["file"].SaveAs(Server.MapPath("~/") + Path.GetFileName(Request.Files["file"].FileName));
    Label1.Text = "上傳成功!";
    }
}

注意兩個(gè)區(qū)別:

一:FileUpload.FileName獲取客戶端上傳文件名(不帶路徑),而file1.PostedFile.FileName 和Request.Files["file"].FileName在不同瀏覽器下情況不同:IE8下獲得的是客戶端上傳文件的完全限定名(帶路徑),谷歌、蘋果等瀏覽器下則仍為文件名(不帶路徑)。

二:FileUpload控件有HasFile屬性,用于判斷用戶是否選擇了上傳文件,而后面兩種方法則需要通過判斷上傳文件大小ContentLength屬性,當(dāng)用戶沒有選擇上傳文件時(shí),該屬性值為0。

可以看出FileUpload封裝程度更高,但靈活性也稍差。

例,Asp.net 文件上傳類(取得文件后綴名,保存文件,加入文字水印)

復(fù)制代碼 代碼如下:

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.Drawing;
using System.IO;
using System.Drawing.Imaging;

namespace EC
{
/// summary>
/// 上傳類
/// /summary>
public class UploadObj
{

public UploadObj()
{
//
// TODO: 在此處添加構(gòu)造函數(shù)邏輯
//
}
/// summary>
/// 允許文件上傳的類型枚舉
/// /summary>
public enum FileType
{
jpg,gif,bmp,png
}

#region 取得文件后綴
/// summary>
/// 取得文件后綴
/// /summary>
/// param name="filename">文件名稱/param>
/// returns>/returns>
public static string GetFileExtends(string filename)
{
string ext = null;
if (filename.IndexOf('.') > 0)
{
string[] fs = filename.Split('.');
ext = fs[fs.Length - 1];
}
return ext;
}
#endregion

#region 檢測文件是否合法
/// summary>
/// 檢測上傳文件是否合法
/// /summary>
/// param name="fileExtends">文件后綴名/param>
/// returns>/returns>
public static bool CheckFileExtends(string fileExtends)
{
bool status = false;
fileExtends = fileExtends.ToLower();
string[] fe = Enum.GetNames(typeof(FileType));
for (int i = 0; i fe.Length; i++)
{
if (fe[i].ToLower() == fileExtends)
{
status = true;
break;
}
}
return status;
}
#endregion

#region 保存文件
/// summary>
/// 保存文件
/// /summary>
/// param name="fpath">全路徑,Server.MapPath()/param>
/// param name="myFileUpload">上傳控件/param>
/// returns>/returns>
public static string PhotoSave(string fpath,FileUpload myFileUpload)
{
string s = "";
string fileExtends = "";
string fileName = myFileUpload.FileName;
if (fileName != "")
{
//取得文件后綴
fileExtends = EC.UploadObj.GetFileExtends(fileName);
if (!EC.UploadObj.CheckFileExtends(fileExtends))
{
EC.MessageObject.ShowPre("上傳文件類型不合法");
}
Random rd = new Random();
s = EC.RandomObject.DateRndName(rd) + "." + fileExtends;
string file = fpath + "\" + s;
try
{
myFileUpload.SaveAs(file);
}
catch (Exception ee)
{
throw new Exception(ee.ToString());
}
}
return s;
}

#endregion

#region 加入文字水印

/// summary>
/// 加入文字水印
/// /summary>
/// param name="fileName">文件名稱路徑(全路徑)/param>
/// param name="text">文件/param>
public void AddTextToImg(string fileName, string text)
{
if (!File.Exists(fileName))
{
throw new FileNotFoundException("文件不存在");
}
if (text == string.Empty)
{
return;
}

System.Drawing.Image image = System.Drawing.Image.FromFile(fileName);
Bitmap bitmap = new Bitmap(image, image.Width, image.Height);
Graphics g = Graphics.FromImage(bitmap);
float fontSize = 12.0f;//字體大小
float textWidth = text.Length * fontSize;//文本的長度
//下面定義一個(gè)矩形區(qū)域,以后在這個(gè)矩形里面畫上白底黑字
float rectX = 0;
float rectY = 0;
float rectWidth = text.Length * (fontSize + 8);
float rectHeight = fontSize + 8;
//聲明矩形域
RectangleF textArea = new RectangleF(rectX, rectY, rectWidth, rectHeight);
Font font = new Font("宋體", fontSize);//定義字體
Brush whiteBrush = new SolidBrush(Color.White);//白筆刷,畫文字用
Brush blackBrush = new SolidBrush(Color.Black);//黑筆刷,畫背景用
g.FillRectangle(blackBrush, rectX, rectY, rectWidth, rectHeight);
g.DrawString(text, font, whiteBrush, textArea);
MemoryStream ms = new MemoryStream();
bitmap.Save(ms, ImageFormat.Jpeg);
//輸出處理后的圖像,這里為了演示方便,我將圖片顯示在頁面中了
//Response.Clear();
//Response.ContentType = "image/jpeg";
//Response.BinaryWrite(ms.ToArray());
g.Dispose();
bitmap.Dispose();
image.Dispose();
}
#endregion
}
}

ASP.NET的弊端

ASP.NET處理文件上傳的最大的問題在于內(nèi)存占用太高,由于將整個(gè)文件載入內(nèi)存進(jìn)行處理,導(dǎo)致如果用戶上傳文件太大,或者同時(shí)上傳的用戶太多,會(huì)造成服務(wù)器端內(nèi)存耗盡。這個(gè)觀點(diǎn)其實(shí)是片面的,對于早期ASP.NET 1.X,為了供程序處理,會(huì)將用戶上傳的內(nèi)容完全載入內(nèi)存,這的確會(huì)帶來問題,但在ASP.NET 2.0中就已經(jīng)會(huì)在用戶上傳數(shù)據(jù)超過一定數(shù)量之后將其存在硬盤中的臨時(shí)文件中,而這點(diǎn)對于開發(fā)人員完全透明,也就是說,開發(fā)人員可以像以前一樣進(jìn)行數(shù)據(jù)流的處理,這個(gè)也在httpRuntime里通過
requestLengthDiskThreshold 屬性來設(shè)置閾值(threshold),其默認(rèn)值為256,即一個(gè)請求內(nèi)容超過256KB時(shí)就會(huì)啟用硬盤作為緩存,這個(gè)閾值和客戶端是否是在上傳內(nèi)容無關(guān),只關(guān)心客戶端發(fā)來的請求大于這個(gè)值。因此,在ASP.NET 2.0中服務(wù)器的內(nèi)存不會(huì)因?yàn)榭蛻舳说漠惓U埱蠖谋M。另外一個(gè)弊端就是當(dāng)請求超過maxRequestLength(默認(rèn)4M)之后,ASP.NET處理程序?qū)⒉粫?huì)處理該請求。這和ASP.NET拋出一個(gè)異常完全不同,這就是為什么如果用戶上傳文件太大,看到的并不是ASP.NET應(yīng)用程序中指定的錯(cuò)誤頁面(或者默認(rèn)的),因?yàn)锳SP.NET還沒有對這個(gè)請求進(jìn)行處理。

還有一個(gè)問題就是處理ASP.NET大文件上傳的超時(shí)。這個(gè)其實(shí)可以通過在運(yùn)行時(shí)讀取web.config中的httpRuntime節(jié),并轉(zhuǎn)化為 HttpRuntimeSection對象或者重寫Page.OnError()來檢測HTTP Code(相應(yīng)代碼)是否為400來處理,這里不再贅述

代碼如下:

復(fù)制代碼 代碼如下:

    System.Configuration.Configuration  
    config = WebConfigurationManager. 
    OpenWebConfiguration("~"); 
    HttpRuntimeSection section = config.GetSection 
    ("system.web/httpRuntime") as HttpRuntimeSection; 
    double maxFileSize = Math.Round 
    (section.MaxRequestLength / 1024.0, 1); 
    string errorString = string.Format("Make sure  
    your file is under {0:0.#} MB.", maxFileSize);

    protected override void OnError(EventArgs e) 
    { 
    HttpContext ctx = HttpContext.Current; 
    Exception exception = ctx.Server.GetLastError (); 

    string errorString =  
"
    Offending URL: " + ctx.Request.Url.ToString () + 
"
    Source: " + exception.Source +  
"
    Message: " + exception.Message + 
"
    Stack trace: " + exception.StackTrace; 

    ctx.Response.Write (errorString); 

    ctx.Server.ClearError (); 

    base.OnError (e); 
    }


對于文件上傳的功能需要較為特別的需求——例如進(jìn)度條提示,ASP.NET封裝的控件〈asp:FileUpload /〉就無能為力了。

好的解決方案

Robert Bazinet建議,最好的解決方案是使用RIA,大多數(shù)情況下,建議用Silverlight或 Flash的上傳組件來替代傳統(tǒng)的FileUpload組件,這類組件不只是提供了更好的上傳體驗(yàn),也比〈input type="file"〉標(biāo)簽在頁面上的文本框、按鈕漂亮,這個(gè)〈input type="file"〉標(biāo)簽并不能夠通過CSS添加樣式,不過也有人嘗試去解決了。至今為止并沒有什么商業(yè)上傳組件使用了Silverlight,不過這里有演示了用Silverlight進(jìn)行多文件上傳的示例程序。當(dāng)然使用Silverlight就可以很輕松的實(shí)現(xiàn)多線程上傳,斷點(diǎn)續(xù)傳這種功能了,這些都不是我要詳細(xì)討論的內(nèi)容,如果有需要可以自己去看下。

可選擇的解決方案

使用〈input type="file" /〉標(biāo)簽所能提供的支持非常有限,一些特殊需求我們不能實(shí)現(xiàn)——或者說是無法輕易地、直接地實(shí)現(xiàn)。所以為了實(shí)現(xiàn)這樣的功能我們每次都要繞一個(gè)大大的彎。為了避免每次實(shí)現(xiàn)相同功能時(shí)都要費(fèi)神費(fèi)時(shí)地走一遍彎路,市面上或者開源界出現(xiàn)了各種上傳組件,上傳組件提供了封裝好的功能,使得我們在實(shí)現(xiàn)文件上傳功能時(shí)變得輕松了很多。例如幾乎所有的上傳組件都直接或間接地提供了進(jìn)度提示的功能,有的提供了當(dāng)前的百分比數(shù)值,有的則直接提供了一套UI;有的組件只提供了簡單的UI,有的卻提供了一整套上傳、刪除的管理界面。此外,有的組件還提供了防止客戶端惡意上傳的能力。

我覺得最好的辦法是在HttpModule里分塊讀取文件并且保持頁面激活的狀態(tài),這樣就不會(huì)超時(shí),同時(shí)也可以跟蹤進(jìn)度或者取消上傳,或者通過 HttpHandler實(shí)現(xiàn),在通過進(jìn)度條給用戶充分提示的同時(shí),也讓開發(fā)人員能夠更好地控制文件大小以及上傳過程中可能出現(xiàn)的異常。上傳組件都是用這些辦法的,我們的選擇有:

FileUploader.NET (MediaChase公司,$310以上)  
RadUpload (Telerik公司,$249)  
NeatUpload (免費(fèi),遵守LGPL協(xié)議) 

NeatUpload是在ASP.NET Pipeline的BeginRequest事件中截獲當(dāng)前的HttpWorkerRequest對象,然后直接調(diào)用其ReadEntityBody等方法獲取客戶端傳遞過來的數(shù)據(jù)流,并加以分析和處理。并通過使用新的請求進(jìn)行輪詢來獲取當(dāng)前上傳的狀態(tài)。關(guān)于NeatUpload和其他開源組件的介紹可以參看JeffreyZhao的在ASP.NET應(yīng)用程序中上傳文件,當(dāng)然他還說了Memba Velodoc XP Edition和swfupload,寫的非常棒!

HttpWorkerRequest實(shí)現(xiàn)介紹

利用隱含的HttpWorkerRequest,用它的GetPreloadedEntityBody和ReadEntityBody方法從IIS為ASP.NET建立的pipe里分塊讀取數(shù)據(jù)可以實(shí)現(xiàn)文件上傳。實(shí)現(xiàn)方法如下:

復(fù)制代碼 代碼如下:

IServiceProvider provider=(IServiceProvider) 
HttpContext.Current; 
HttpWorkerRequest wr=(HttpWorkerRequest) 
provider.GetService(typeof(HttpWorkerRequest)); 
byte[] bs=wr.GetPreloadedEntityBody(); 
if(!wr.IsEntireEntityBodyIsPreloaded()) 

int n=1024; 
byte[] bs2=new byte[n]; 
while(wr.ReadEntityBody(bs2,n) 〉0) 


}

您可能感興趣的文章:
  • asp 中常用的文件處理函數(shù)
  • ASP.NET MVC處理文件上傳的小例子
  • asp.net 文件上傳實(shí)例匯總
  • ASP.NET讓FileUpload控件支持瀏覽自動(dòng)上傳功能的解決方法
  • asp.net fileupload控件上傳文件與多文件上傳
  • asp.net FileUpload控件實(shí)現(xiàn)文件格式判斷與文件大小限制
  • ASP.NET實(shí)現(xiàn)的簡單易用文件上傳類
  • ASP.NET對大文件上傳的解決方案
  • asp.net批量多選文件上傳解決方案
  • ASP.NET設(shè)計(jì)FTP文件上傳的解決方案
  • asp.net文件上傳帶進(jìn)度條實(shí)現(xiàn)案例(多種風(fēng)格)
  • asp.net文件上傳解決方案(圖片上傳、單文件上傳、多文件上傳、檢查文件類型)
  • ASP.NET MVC5實(shí)現(xiàn)文件上傳與地址變化處理(5)
  • ASP.NET文件處理如何操作

標(biāo)簽:棗莊 拉薩 咸寧 攀枝花 POS機(jī) 益陽 南平 廈門

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《asp.net文件上傳示例分享》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266