ASP.NET中的檔案上傳下載方法集合

來源:互聯網
上載者:User
本文總結了在ASP.NET中一些檔案上傳下載的方法。ASP.NET中的檔案上傳下載是我們經常要用到的技術。檔案的上傳下載是我們在實際項目開發過程中經常需要用到的技術,這裡給出幾種常見的方法,本文主要內容包括:1、如何解決檔案上傳大小的限制2、以檔案形式儲存到伺服器3、轉換成二進位位元組流儲存到資料庫以及下載方法4、上傳Internet上的資源ASP.NET中檔案上傳下載,第一部分:首先我們來說一下如何解決asp.net中的檔案上傳大小限制的問題,我們知道在預設情況下asp.net的檔案上傳大小限制為2M,一般情況下,我們可以採用更改Web.Config檔案來自訂最大檔案大小,如下:這樣上傳檔案的最大值就變成了4M,但這樣並不能讓我們無限的擴大 MaxRequestLength的值,因為asp.net會將全部檔案載入記憶體後,再加以處理。解決的方法是利用隱含的 HttpWorkerRequest,用它的GetPreloadedEntityBody和ReadEntityBody方法從IIS為asp.net 建立的pipe裡分塊讀取資料。實現方法如下: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)    {   ..    }   }   這樣就可以解決了大檔案的上傳問題了。ASP.NET中檔案上傳下載,第二部分:下面我們來介紹如何以檔案形式將用戶端的一個檔案上傳到伺服器並返回上傳檔案的一些基本資料。首先我們定義一個類,用來儲存上傳的檔案的資訊(返回時需要)。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);    //    //根據類型確定檔案格式    //    AppConfig app = new AppConfig();    string format = app.GetPath("FileUpLoad/Format");    //    //如果格式都不符合則返回    //    if(format.IndexOf(fileExtension)==-1)    {   throw new ApplicationException("上傳資料格式不合法");    }    //    //根據日期和隨機數產生隨機的檔案名稱    //    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);    //判斷路徑是否存在,若不存在則建立路徑    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;   }   然後我們在上傳檔案的時候就可以調用這個方法了,將返回的檔案資訊儲存到資料庫中,至於下載,就直接開啟那個路徑就OK了。ASP.NET中檔案上傳下載,第三部分:這裡我們主要說一下如何以二進位的形式上傳檔案以及下載。首先說上傳,方法如下: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;   }   這個方法返回的就是上傳的檔案的二進位位元組流,這樣我們就可以將它儲存到資料庫了。下面說一下這種形式的下載,也許你會想到這種方式的下載就是建立一個 aspx頁面,然後在它的Page_Load()事件裡取出二進位位元組流,然後再讀出來就可以了,其實這種方法是不可取的,在實際的運用中也許會出現無法開啟某網站的錯誤,我一般採用下面的方法:首先,在Web.config中加入:<add verb="*" path="openfile.aspx" type="RuixinOA.Web.BaseClass.OpenFile, RuixinOA.Web"/>   這表示我開啟openfile.aspx這個頁面時,系統就會自動轉到執行RuixinOA.Web.BaseClass.OpenFile 這個類裡的方法,具體實現如下: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   {    /**////    /// NetUFile 的摘要說明。    ///    public class OpenFile : IHttpHandler    {   public void ProcessRequest(HttpContext context)   {    //從資料庫中取出要下載的檔案資訊    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;}   }    }   }   執行上面的方法後,系統會提示使用者選擇直接開啟還是下載。這一部分我們就說到這裡。ASP.NET中檔案上傳下載,第四部分:這一部分主要說如何上傳一個Internet上的資源到伺服器。首先需要引用 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上讀取檔案,因此可以很好的解決這個問題。
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.