asp.net下載檔案方法

來源:互聯網
上載者:User

/*
* 輸入參數
* _Request: Page.Request 對象
* _Response: Page.Response 對象
* _fileName: 下載檔案名稱
* _fullPath: 帶檔案名稱下載路徑
* _speed 每秒允許下載的位元組數
* 返回是否成功
*/

public static bool ResponseFile(HttpRequest _Request,HttpResponse _Response,string _fileName,string _fullPath, long _speed) {        try {            FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);            BinaryReader br = new BinaryReader(myFile);            try {                _Response.AddHeader("Accept-Ranges", "bytes");                _Response.Buffer = false;                long fileLength = myFile.Length;                long startBytes = 0;                int pack = 10240; //10K bytes                    //int sleep = 200; //每秒5次 即5*10K bytes每秒                    int sleep = (int)Math.Floor(1000 * pack / _speed) + 1;                if (_Request.Headers["Range"] != null) {                    _Response.StatusCode = 206;                    string[] range = _Request.Headers["Range"].Split(new char[] {@#=@#, @#-@#});                    startBytes = Convert.ToInt64(range[1]);                }                _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());                if (startBytes != 0) {                    _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength-1, fileLength));                }                _Response.AddHeader("Connection", "Keep-Alive");                _Response.ContentType = "application/octet-stream";                _Response.AddHeader("Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(_fileName,System.Text.Encoding.UTF8) );                br.BaseStream.Seek(startBytes, SeekOrigin.Begin);                int maxCount = (int) Math.Floor((fileLength - startBytes) / pack) + 1;                for (int i = 0;i < maxCount;i++) {                    if (_Response.IsClientConnected) {                            _Response.BinaryWrite(br.ReadBytes(pack));                        Thread.Sleep(sleep);                    }else {                            i=maxCount;                    }                }            }catch {                    return false;            }finally {                    br.Close();                myFile.Close();            }        }catch {                return false;        }        return true; }
 

調用例

Page.Response.Clear(); bool success = ResponseFile(Page.Request, Page.Response, "filename", @"C:\download.date", 1024000); if(!success)            Response.Write("下載檔案出錯!"); Page.Response.End();
 
如何通過ASP.NET來下載檔案,這個問題我們經常遇到,把常用的方法總結到一起,學習學習。當我們要讓使用者下載一個檔案,最簡單的方式是通過Response.Redirect指令: 

Response.Redirect("test.doc")


您可以把上面這行指令放在Button的Click事件當中,當使用者點擊按鈕之後,網頁就會被轉址到該word檔,造成下載的效果。

但是這樣的下載有幾個問題:

1、無法下載不存在的檔案:例如,我們若是想把程式動態(臨時)產生的文字,當作一個檔案下載的時候(也就是該檔案其實原先並不是真的存在,而是動態產生的),就無法下載。

2、無法下載儲存於資料庫中的檔案:這是類似的問題,該檔案並沒有真的存在,只是被存放在資料庫中的某個位置(某筆記錄中的某個欄位)的時候,就無法下載。

3、無法下載不存在於Web檔案夾中的檔案:檔案確實存在,但該檔案夾並不是可以分享出來的Web檔案夾,例如,該檔案的位置在C:\winnt,您總不會想要把該檔案夾當作Web檔案夾吧?這時候,由於您無法使用Redirect指向該位置,所以無法下載。

4、下載檔案後,原本的頁面將會消失。

典型的狀況是,我們要讓使用者下載一個.txt檔案或是.csv格式的Excel檔案,但是...

1、這個檔案可能是通過ASP.NET程式動態產生的,而不是確實存在於Server端的檔案;

2、或是它雖然存在於伺服器端的某個實體位置,但我們並不想暴露這個位置(如果這個位置公開,很可能沒有許可權的使用者也可以在網址欄上輸入URL直接取得!!!)

3、或是這個位置並不在網站虛擬路徑所在的檔案夾中。(例如C:\Windows\System32...)


   //TransmitFile實現下載

    protected void Button1_Click(object sender, EventArgs e)

    {

        /*

        微軟為Response對象提供了一個新的方法TransmitFile來解決使用Response.BinaryWrite

        下載超過400mb的檔案時導致Aspnet_wp.exe進程回收而無法成功下載的問題。

        代碼如下:

        */

        Response.ContentType = "application/x-zip-compressed";

        Response.AddHeader("Content-Disposition", "attachment;filename=z.zip");

        string filename = Server.MapPath("DownLoad/z.zip");

        Response.TransmitFile(filename);

    }

    //WriteFile實現下載

    protected void Button2_Click(object sender, EventArgs e)

    {

        /*

        using System.IO;

        */

        string fileName = "asd.txt";//用戶端儲存的檔案名稱

        string filePath = Server.MapPath("DownLoad/aaa.txt");//路徑

        FileInfo fileInfo = new FileInfo(filePath);

        Response.Clear();

        Response.ClearContent();

        Response.ClearHeaders();

        Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);

        Response.AddHeader("Content-Length", fileInfo.Length.ToString());

        Response.AddHeader("Content-Transfer-Encoding", "binary");

        Response.ContentType = "application/octet-stream";

        Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");

        Response.WriteFile(fileInfo.FullName);

        Response.Flush();

        Response.End();

    }

    //WriteFile分塊下載

    protected void Button3_Click(object sender, EventArgs e)

    {

        string fileName = "aaa.txt";//用戶端儲存的檔案名稱

        string filePath = Server.MapPath("DownLoad/aaa.txt");//路徑

        System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);

        if (fileInfo.Exists == true)

        {

            const long ChunkSize = 102400;//100K 每次讀取檔案,唯讀取100K,這樣可以緩解伺服器的壓力

            byte[] buffer = new byte[ChunkSize];

            Response.Clear();

            System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);

            long dataLengthToRead = iStream.Length;//擷取下載的檔案總大小

            Response.ContentType = "application/octet-stream";

            Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName));

            while (dataLengthToRead > 0 && Response.IsClientConnected)

            {

                int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//讀取的大小

                Response.OutputStream.Write(buffer, 0, lengthRead);

                Response.Flush();

                dataLengthToRead = dataLengthToRead - lengthRead;

            }

            Response.Close();

        }

    }

    //流方式下載

    protected void Button4_Click(object sender, EventArgs e)

    {

        string fileName = "aaa.txt";//用戶端儲存的檔案名稱

        string filePath = Server.MapPath("DownLoad/aaa.txt");//路徑

        //以字元流的形式下載檔案

        FileStream fs = new FileStream(filePath, FileMode.Open);

        byte[] bytes = new byte[(int)fs.Length];

        fs.Read(bytes, 0, bytes.Length);

        fs.Close();

        Response.ContentType = "application/octet-stream";

        //通知瀏覽器下載檔案而不是開啟

        Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));

        Response.BinaryWrite(bytes);

        Response.Flush();

        Response.End();

    }

//----------------------------------------------------------


public void DownloadFile( System.Web.UI.Page WebForm,String FileNameWhenUserDownload ,String FileBody )

{

  WebForm.Response.ClearHeaders();

  WebForm.Response.Clear();

  WebForm.Response.Expires = 0;

  WebForm.Response.Buffer = true;

  WebForm.Response.AddHeader("Accept-Language", "zh-tw");

  //'檔案名稱

  WebForm.Response.AddHeader("content-disposition", "attachment; filename='"+System.Web.HttpUtility.UrlEncode(FileNameWhenUserDownload, System.Text.Encoding.UTF8)+"'");

  WebForm.Response.ContentType = "Application/octet-stream";

  //'檔案內容

  WebForm.Response.Write(FileBody);//-----------

    WebForm.Response.End();

}

//上面這段代碼是下載一個動態產生的文字檔,若這個檔案已經存在於伺服器端的實體路徑,則可以通過下面的函數:

public void DownloadFileByFilePath( System.Web.UI.Page WebForm,String FileNameWhenUserDownload ,String FilePath )

{

  WebForm.Response.ClearHeaders();

  WebForm.Response.Clear();

  WebForm.Response.Expires = 0;

    WebForm.Response.Buffer = true;

  WebForm.Response.AddHeader("Accept-Language", "zh-tw");

  //檔案名稱

  WebForm.Response.AddHeader("content-disposition", "attachment; filename='" + System.Web.HttpUtility.UrlEncode(FileNameWhenUserDownload, System.Text.Encoding.UTF8) +"'" );

  WebForm.Response.ContentType = "Application/octet-stream";

  //檔案內容

  WebForm.Response.Write(System.IO.File.ReadAllBytes(FilePath));//---------

  WebForm.Response.End();

}

 

 

 

下面是更詳細的ContentType
'ez' => 'application/andrew-inset',
'hqx' => 'application/mac-binhex40',
'cpt' => 'application/mac-compactpro',
'doc' => 'application/msword',
'bin' => 'application/octet-stream',
'dms' => 'application/octet-stream',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'exe' => 'application/octet-stream',
'class' => 'application/octet-stream',
'so' => 'application/octet-stream',
'dll' => 'application/octet-stream',
'oda' => 'application/oda',
'pdf' => 'application/pdf',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
'smi' => 'application/smil',
'smil' => 'application/smil',
'mif' => 'application/vnd.mif',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
'wbxml' => 'application/vnd.wap.wbxml',
'wmlc' => 'application/vnd.wap.wmlc',
'wmlsc' => 'application/vnd.wap.wmlscriptc',
'bcpio' => 'application/x-bcpio',
'vcd' => 'application/x-cdlink',
'pgn' => 'application/x-chess-pgn',
'cpio' => 'application/x-cpio',
'csh' => 'application/x-csh',
'dcr' => 'application/x-director',
'dir' => 'application/x-director',
'dxr' => 'application/x-director',
'dvi' => 'application/x-dvi',
'spl' => 'application/x-futuresplash',
'gtar' => 'application/x-gtar',
'hdf' => 'application/x-hdf',
'js' => 'application/x-javascript',
'skp' => 'application/x-koan',
'skd' => 'application/x-koan',
'skt' => 'application/x-koan',
'skm' => 'application/x-koan',
'latex' => 'application/x-latex',
'nc' => 'application/x-netcdf',
'cdf' => 'application/x-netcdf',
'sh' => 'application/x-sh',
'shar' => 'application/x-shar',
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'sv4cpio' => 'application/x-sv4cpio',
'sv4crc' => 'application/x-sv4crc',
'tar' => 'application/x-tar',
'tcl' => 'application/x-tcl',
'tex' => 'application/x-tex',
'texinfo' => 'application/x-texinfo',
'texi' => 'application/x-texinfo',
't' => 'application/x-troff',
'tr' => 'application/x-troff',
'roff' => 'application/x-troff',
'man' => 'application/x-troff-man',
'me' => 'application/x-troff-me',
'ms' => 'application/x-troff-ms',
'ustar' => 'application/x-ustar',
'src' => 'application/x-wais-source',
'xhtml' => 'application/xhtml+xml',
'xht' => 'application/xhtml+xml',
'zip' => 'application/zip',
'au' => 'audio/basic',
'snd' => 'audio/basic',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'kar' => 'audio/midi',
'mpga' => 'audio/mpeg',
'mp2' => 'audio/mpeg',
'mp3' => 'audio/mpeg',
'aif' => 'audio/x-aiff',
'aiff' => 'audio/x-aiff',
'aifc' => 'audio/x-aiff',
'm3u' => 'audio/x-mpegurl',
'ram' => 'audio/x-pn-realaudio',
'rm' => 'audio/x-pn-realaudio',
'rpm' => 'audio/x-pn-realaudio-plugin',
'ra' => 'audio/x-realaudio',
'wav' => 'audio/x-wav',
'pdb' => 'chemical/x-pdb',
'xyz' => 'chemical/x-xyz',
'bmp' => 'image/bmp',
'gif' => 'image/gif',
'ief' => 'image/ief',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'jpe' => 'image/jpeg',
'png' => 'image/png',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'djvu' => 'image/vnd.djvu',
'djv' => 'image/vnd.djvu',
'wbmp' => 'image/vnd.wap.wbmp',
'ras' => 'image/x-cmu-raster',
'pnm' => 'image/x-portable-anymap',
'pbm' => 'image/x-portable-bitmap',
'pgm' => 'image/x-portable-graymap',
'ppm' => 'image/x-portable-pixmap',
'rgb' => 'image/x-rgb',
'xbm' => 'image/x-xbitmap',
'xpm' => 'image/x-xpixmap',
'xwd' => 'image/x-xwindowdump',
'igs' => 'model/iges',
'iges' => 'model/iges',
'msh' => 'model/mesh',
'mesh' => 'model/mesh',
'silo' => 'model/mesh',
'wrl' => 'model/vrml',
'vrml' => 'model/vrml',
'css' => 'text/css',
'html' => 'text/html',
'htm' => 'text/html',
'asc' => 'text/plain',
'txt' => 'text/plain',
'rtx' => 'text/richtext',
'rtf' => 'text/rtf',
'sgml' => 'text/sgml',
'sgm' => 'text/sgml',
'tsv' => 'text/tab-separated-values',
'wml' => 'text/vnd.wap.wml',
'wmls' => 'text/vnd.wap.wmlscript',
'etx' => 'text/x-setext',
'xsl' => 'text/xml',
'xml' => 'text/xml',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpe' => 'video/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
'mxu' => 'video/vnd.mpegurl',
'avi' => 'video/x-msvideo',
'movie' => 'video/x-sgi-movie',
'ice' => 'x-conference/x-cooltalk'

 

 

 

轉載: http://www.cnblogs.com/kingkoo/archive/2009/08/08/1541593.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.