asp.net(C#)中上傳大文件的幾中常見應(yīng)用方法
更新時間:2008年11月25日 10:05:46 作者:
最近博客需要做一個文件上下載功能,我從網(wǎng)上找了點資料,整理了下希望對大家有幫助!
幾種常見的方法,本文主要內(nèi)容包括:
第一部分:首先我們來說一下如何解決ASP.net中的文件上傳大小限制的問題,我們知道在默認情況下ASP.NET的文件上傳大小限制為2M,一般情況下,我們可以采用更改Web.Config文件來自定義最大文件大小,如下:
這樣上傳文件的最大值就變成了4M,但這樣并不能讓我們無限的擴大 MaxRequestLength的值,因為ASP.NET會將全部文件載入內(nèi)存后,再加以處理。解決的方法是利用隱含的 HttpWorkerRequest,用它的GetPreloadedEntityBody和ReadEntityBody方法從IIS為ASP.NET 建立的pipe里分塊讀取數(shù)據(jù)。實現(xiàn)方法如下:
IServiceProvidERProvider=(IServiceProvider)HttpContext.Current;
HttpWorkerRequestwr=(HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
byte[]bs=wr.GetPreloadedEntityBody();
if(!wr.IsEntireEntityBodyIsPreloaded())
{
intn=1024;
byte[]bs2=newbyte[n];
while(wr.ReadEntityBody(bs2,n)>0)
{
..
}
}
這樣就可以解決了大文件的上傳問題了。
第二部分:下面我們來介紹如何以文件形式將客戶端的一個文件上傳到服務(wù)器并返回上傳文件的一些基本信息。
首先我們定義一個類,用來存儲上傳的文件的信息(返回時需要)。
public class FileUpLoad
{
public FileUpLoad()
{}
/// 上傳文件名稱
public string FileName
{
get
{
return fileName;
}
set
{
fileName = value;
}
}
private string fileName;
/// 上傳文件路徑
public string FilePath
{
get
{
return filepath;
}
set
{
filepath = value;
}
}
private string filepath;
/// 文件擴展名
public string FileExtension
{
get
{
return fileExtension;
}
set
{
fileExtension = value;
}
}
private string fileExtension;
}
另外我們還可以在配置文件中限制上傳文件的格式(App.Config):
<?XML version="1.0" encoding="gb2312" ?>
<Application>
<FileUpLoad>
<Format>.jpg|.gif|.png|.bmp
</FileUpLoad>
</Application> 這樣我們就可以開始寫我們的上傳文件的方法了,如下: public FileUpLoad UpLoadFile(HtmlInputFile InputFile,string filePath,string myfileName,bool isRandom)
{
FileUpLoad fp = new FileUpLoad();
string fileName,fileExtension;
string saveName;
//建立上傳對象
HttpPostedFile postedFile = InputFile.PostedFile;
fileName = System.IO.Path.GetFileName(postedFile.FileName);
fileExtension = System.IO.Path.GetExtension(fileName);
//根據(jù)類型確定文件格式
AppConfig app = new AppConfig();
string format = app.GetPath("FileUpLoad/Format");
//如果格式都不符合則返回
if(format.IndexOf(fileExtension)==-1)
{
throw new ApplicationException("上傳數(shù)據(jù)格式不合法");
}
//
//根據(jù)日期和隨機數(shù)生成隨機的文件名
//
if(myfileName != string.Empty)
{
fileName = myfileName;
}
if(isRandom)
{
Random objRand = new Random();
System.DateTime date = DateTime.Now;
//生成隨機文件名
saveName = date.Year.ToString() + date.Month.ToString() + date.Day.ToString() + date.Hour.ToString() + date.Minute.ToString() + date.Second.ToString() + Convert.ToString(objRand.Next(99)*97 + 100);
fileName = saveName + fileExtension;
}
string phyPath = HttpContext.Current.Request.MapPath(filePath);
//判斷路徑是否存在,若不存在則創(chuàng)建路徑
DirectoryInfo upDir = new DirectoryInfo(phyPath);
if(!upDir.Exists)
{
upDir.Create();
}
//保存文件
try
{
postedFile.SaveAs(phyPath + fileName);
fp.FilePath = filePath + fileName;
fp.FileExtension = fileExtension;
fp.FileName = fileName;
}
catch
{
throw new ApplicationException("上傳失敗!");
}
//返回上傳文件的信息
return fp;
}
然后我們在上傳文件的時候就可以調(diào)用這個方法了,將返回的文件信息保存到數(shù)據(jù)庫中,至于下載,就直接打開那個路徑就OK了。
第三部分:這里我們主要說一下如何以二進制的形式上傳文件以及下載。首先說上傳,方法如下:
public byte[] UpLoadFile(HtmlInputFile f_IFile)
{
//獲取由客戶端指定的上傳文件的訪問
HttpPostedFile upFile=f_IFile.PostedFile;
//得到上傳文件的長度
int upFileLength=upFile.ContentLength;
//得到上傳文件的客戶端MIME類型
string contentType = upFile.ContentType;
byte[] FileArray=new Byte[upFileLength];
Stream fileStream=upFile.InputStream;
fileStream.Read(FileArray,0,upFileLength);
return FileArray;
}
這個方法返回的就是上傳的文件的二進制字節(jié)流,這樣我們就可以將它保存到數(shù)據(jù)庫了。下面說一下這種形式的下載,也許你會想到這種方式的下載就是新建一個 aspx頁面,然后在它的Page_Load()事件里取出二進制字節(jié)流,然后再讀出來就可以了,其實這種方法是不可取的,在實際的運用中也許會出現(xiàn)無法打開某站點的錯誤,我一般采用下面的方法:
首先,在Web.config中加入:?。糰dd verb="*" path="openfile.aspx" type="RuixinOA.Web.BaseClass.OpenFile, RuixinOA.Web"/> 這表示我打開openfile.aspx這個頁面時,系統(tǒng)就會自動轉(zhuǎn)到執(zhí)行RuixinOA.Web.BaseClass.OpenFile 這個類里的方法,具體實現(xiàn)如下:
using System;
using System.Data;
using System.Web;
using System.IO;
using Ruixin.WorkFlowDB;
using RXSuite.Base;
using RXSuite.Component;
using RuixinOA.BusinessFacade;
namespace RuixinOA.Web.BaseClass
{
public class OpenFile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//從數(shù)據(jù)庫中取出要下載的文件信息
RuixinOA.BusinessFacade.RX_OA_FileManager os = new RX_OA_FileManager();
EntityData data = os.GetFileDetail(id);
if(data != null && data.Tables["RX_OA_File"].Rows.Count >0)
{
DataRow dr = (DataRow)data.Tables["RX_OA_File"].Rows[0];
context.Response.Buffer = true;
context.Response.Clear();
context.Response.ContentType = dr["CContentType"].ToString();
context.Response.AddHeader("Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(dr["CTitle"].ToString()));
context.Response.BinaryWrite((Byte[])dr["CContent"]);
context.Response.Flush();
context.Response.End();
}
}
public bool IsReusable
{
get { return true;}
}
}
}
執(zhí)行上面的方法后,系統(tǒng)會提示用戶選擇直接打開還是下載。這一部分我們就說到這里。
第四部分:這一部分主要說如何上傳一個Internet上的資源到服務(wù)器。
首先需要引用 System.Net 這個命名空間,然后操作如下: HttpWebRequest hwq = (HttpWebRequest)WebRequest.Create("http://localhost/pwtest/webform1.aspx");
HttpWebResponse hwr = (HttpWebResponse)hwq.GetResponse();
byte[] bytes = new byte[hwr.ContentLength];
Stream stream = hwr.GetResponseStream();
stream.Read(bytes,0,Convert.ToInt32(hwr.ContentLength));
//HttpContext.Current.Response.BinaryWrite(bytes);
HttpWebRequest 可以從Internet上讀取文件,因此可以很好的解決這個問題。
第一部分:首先我們來說一下如何解決ASP.net中的文件上傳大小限制的問題,我們知道在默認情況下ASP.NET的文件上傳大小限制為2M,一般情況下,我們可以采用更改Web.Config文件來自定義最大文件大小,如下:
這樣上傳文件的最大值就變成了4M,但這樣并不能讓我們無限的擴大 MaxRequestLength的值,因為ASP.NET會將全部文件載入內(nèi)存后,再加以處理。解決的方法是利用隱含的 HttpWorkerRequest,用它的GetPreloadedEntityBody和ReadEntityBody方法從IIS為ASP.NET 建立的pipe里分塊讀取數(shù)據(jù)。實現(xiàn)方法如下:
IServiceProvidERProvider=(IServiceProvider)HttpContext.Current;
HttpWorkerRequestwr=(HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
byte[]bs=wr.GetPreloadedEntityBody();
if(!wr.IsEntireEntityBodyIsPreloaded())
{
intn=1024;
byte[]bs2=newbyte[n];
while(wr.ReadEntityBody(bs2,n)>0)
{
..
}
}
這樣就可以解決了大文件的上傳問題了。
第二部分:下面我們來介紹如何以文件形式將客戶端的一個文件上傳到服務(wù)器并返回上傳文件的一些基本信息。
首先我們定義一個類,用來存儲上傳的文件的信息(返回時需要)。
public class FileUpLoad
{
public FileUpLoad()
{}
/// 上傳文件名稱
public string FileName
{
get
{
return fileName;
}
set
{
fileName = value;
}
}
private string fileName;
/// 上傳文件路徑
public string FilePath
{
get
{
return filepath;
}
set
{
filepath = value;
}
}
private string filepath;
/// 文件擴展名
public string FileExtension
{
get
{
return fileExtension;
}
set
{
fileExtension = value;
}
}
private string fileExtension;
}
另外我們還可以在配置文件中限制上傳文件的格式(App.Config):
<?XML version="1.0" encoding="gb2312" ?>
<Application>
<FileUpLoad>
<Format>.jpg|.gif|.png|.bmp
</FileUpLoad>
</Application> 這樣我們就可以開始寫我們的上傳文件的方法了,如下: public FileUpLoad UpLoadFile(HtmlInputFile InputFile,string filePath,string myfileName,bool isRandom)
{
FileUpLoad fp = new FileUpLoad();
string fileName,fileExtension;
string saveName;
//建立上傳對象
HttpPostedFile postedFile = InputFile.PostedFile;
fileName = System.IO.Path.GetFileName(postedFile.FileName);
fileExtension = System.IO.Path.GetExtension(fileName);
//根據(jù)類型確定文件格式
AppConfig app = new AppConfig();
string format = app.GetPath("FileUpLoad/Format");
//如果格式都不符合則返回
if(format.IndexOf(fileExtension)==-1)
{
throw new ApplicationException("上傳數(shù)據(jù)格式不合法");
}
//
//根據(jù)日期和隨機數(shù)生成隨機的文件名
//
if(myfileName != string.Empty)
{
fileName = myfileName;
}
if(isRandom)
{
Random objRand = new Random();
System.DateTime date = DateTime.Now;
//生成隨機文件名
saveName = date.Year.ToString() + date.Month.ToString() + date.Day.ToString() + date.Hour.ToString() + date.Minute.ToString() + date.Second.ToString() + Convert.ToString(objRand.Next(99)*97 + 100);
fileName = saveName + fileExtension;
}
string phyPath = HttpContext.Current.Request.MapPath(filePath);
//判斷路徑是否存在,若不存在則創(chuàng)建路徑
DirectoryInfo upDir = new DirectoryInfo(phyPath);
if(!upDir.Exists)
{
upDir.Create();
}
//保存文件
try
{
postedFile.SaveAs(phyPath + fileName);
fp.FilePath = filePath + fileName;
fp.FileExtension = fileExtension;
fp.FileName = fileName;
}
catch
{
throw new ApplicationException("上傳失敗!");
}
//返回上傳文件的信息
return fp;
}
然后我們在上傳文件的時候就可以調(diào)用這個方法了,將返回的文件信息保存到數(shù)據(jù)庫中,至于下載,就直接打開那個路徑就OK了。
第三部分:這里我們主要說一下如何以二進制的形式上傳文件以及下載。首先說上傳,方法如下:
public byte[] UpLoadFile(HtmlInputFile f_IFile)
{
//獲取由客戶端指定的上傳文件的訪問
HttpPostedFile upFile=f_IFile.PostedFile;
//得到上傳文件的長度
int upFileLength=upFile.ContentLength;
//得到上傳文件的客戶端MIME類型
string contentType = upFile.ContentType;
byte[] FileArray=new Byte[upFileLength];
Stream fileStream=upFile.InputStream;
fileStream.Read(FileArray,0,upFileLength);
return FileArray;
}
這個方法返回的就是上傳的文件的二進制字節(jié)流,這樣我們就可以將它保存到數(shù)據(jù)庫了。下面說一下這種形式的下載,也許你會想到這種方式的下載就是新建一個 aspx頁面,然后在它的Page_Load()事件里取出二進制字節(jié)流,然后再讀出來就可以了,其實這種方法是不可取的,在實際的運用中也許會出現(xiàn)無法打開某站點的錯誤,我一般采用下面的方法:
首先,在Web.config中加入:?。糰dd verb="*" path="openfile.aspx" type="RuixinOA.Web.BaseClass.OpenFile, RuixinOA.Web"/> 這表示我打開openfile.aspx這個頁面時,系統(tǒng)就會自動轉(zhuǎn)到執(zhí)行RuixinOA.Web.BaseClass.OpenFile 這個類里的方法,具體實現(xiàn)如下:
using System;
using System.Data;
using System.Web;
using System.IO;
using Ruixin.WorkFlowDB;
using RXSuite.Base;
using RXSuite.Component;
using RuixinOA.BusinessFacade;
namespace RuixinOA.Web.BaseClass
{
public class OpenFile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//從數(shù)據(jù)庫中取出要下載的文件信息
RuixinOA.BusinessFacade.RX_OA_FileManager os = new RX_OA_FileManager();
EntityData data = os.GetFileDetail(id);
if(data != null && data.Tables["RX_OA_File"].Rows.Count >0)
{
DataRow dr = (DataRow)data.Tables["RX_OA_File"].Rows[0];
context.Response.Buffer = true;
context.Response.Clear();
context.Response.ContentType = dr["CContentType"].ToString();
context.Response.AddHeader("Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(dr["CTitle"].ToString()));
context.Response.BinaryWrite((Byte[])dr["CContent"]);
context.Response.Flush();
context.Response.End();
}
}
public bool IsReusable
{
get { return true;}
}
}
}
執(zhí)行上面的方法后,系統(tǒng)會提示用戶選擇直接打開還是下載。這一部分我們就說到這里。
第四部分:這一部分主要說如何上傳一個Internet上的資源到服務(wù)器。
首先需要引用 System.Net 這個命名空間,然后操作如下: HttpWebRequest hwq = (HttpWebRequest)WebRequest.Create("http://localhost/pwtest/webform1.aspx");
HttpWebResponse hwr = (HttpWebResponse)hwq.GetResponse();
byte[] bytes = new byte[hwr.ContentLength];
Stream stream = hwr.GetResponseStream();
stream.Read(bytes,0,Convert.ToInt32(hwr.ContentLength));
//HttpContext.Current.Response.BinaryWrite(bytes);
HttpWebRequest 可以從Internet上讀取文件,因此可以很好的解決這個問題。
相關(guān)文章
asp.net下用Aspose.Words for .NET動態(tài)生成word文檔中的圖片或水印的方法
本文詳細講解如何使用Aspose.Words for .NET的組件來生成word文檔與水印的方法,請看本文內(nèi)容。2010-04-04ASP.NET性能優(yōu)化小結(jié)(ASP.NET&C#)
ASP.NET性能優(yōu)化,提高頁面的執(zhí)行效率與下載速度,等很多需要考慮的細節(jié),編程人員值得參考下。2011-01-01Visual Studio 2017 針對移動開發(fā)的新特性匯總
Visual Studio是世界上最好的IDE之一,下面就讓我們一起來看看Visual Studio 2017中有哪些功能使得移動開發(fā)變得更加容易,感興趣的朋友通過本文學(xué)習(xí)下吧2017-05-05ASP.NET中Session和Cache的區(qū)別總結(jié)
這篇文章主要介紹了ASP.NET中Session和Cache的區(qū)別總結(jié),本文結(jié)合使用經(jīng)驗,總結(jié)出了5點Session緩存和Cache緩存的區(qū)別,需要的朋友可以參考下2015-06-06