Asp.net File Download Method

Source: Internet
Author: User
Tags gtar

/*
* Input parameters
* _ Request: page. Request object
* _ Response: page. Response object
* _ Filename: Download file name
* _ Fullpath: Download path with file name
* _ Speed: the number of bytes that can be downloaded per second.
* Whether the returned result is successful
*/

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 startbyt Es = 0; int pack = 10240; // 10 K Bytes // int sleep = 200; // 5 times per second, that is, 5*10 K Bytes int sleep = (INT) math. floor (1000 * pack/_ speed) + 1; if (_ request. headers ["range"]! = NULL) {_ response. status Code = 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 ;}
 

Call example

Page. response. clear (); bool success = responsefile (page. request, page. response, "FILENAME", @ "C: \ Download. date ", 1024000); If (! Success) response. Write ("An error occurred while downloading the file! "); Page. response. End ();
 
How to download files through ASP. NET is a problem that we often encounter. We will summarize common methods and learn from them. When we want users to download an object, the simplest way is through the response. Redirect command:

Response. Redirect ("test.doc ")


You can place the preceding command line in the Click Event of the button. When you click the button, the webpage will be directed to the Word file, resulting in download effect.

However, there are several problems with this download:

1. files that do not exist cannot be downloaded. For example, if we want to generate dynamic (temporary) text in the program, when a file is downloaded (that is, the file does not actually exist, but is generated dynamically), it cannot be downloaded.

2. files stored in the database cannot be downloaded. This is a similar problem. The file does not exist, but is stored in a certain location in the database (a column in a record) and cannot be downloaded.

3. files that do not exist in the Web Folder cannot be downloaded: The file exists, but the folder is not a web folder that can be shared. For example, the file is located at c: \ WINNT, you never want to treat this folder as a web folder? At this time, you cannot use redirect to point to this location, so you cannot download.

4. After the file is downloaded, the original page will disappear.

However, we want the user to download a. txt file or an Excel file in. CSV format,...

1. This file may be dynamically generated through ASP. NET programs, rather than files on the server;

2. Although it exists in a physical location on the server side, we do not want to expose this location (if this location is public, users who do not have the permission can also enter a URL in the URL bar to directly obtain it !!!)

3. The location is not in the folder where the website virtual path is located. (For example, c: \ windows \ system32 ...)


// Download transmitfile

Protected void button#click (Object sender, eventargs E)

{

/*

Microsoft provides a new transmitfile method for the response object to solve the problem of using response. binarywrite

When a file with more than Mbit/s is downloaded, The aspnet_wp.exe process cannot be recycled.

The Code is as follows:

*/

Response. contenttype = "application/X-zip-compressed ";

Response. addheader ("content-disposition", "attachment?filename=z.zip ");

String filename = server. mappath ("download/z.zip ");

Response. transmitfile (filename );

}

// Download writefile

Protected void button2_click (Object sender, eventargs E)

{

/*

Using system. IO;

*/

String filename = "asd.txt"; // file name saved by the client

String filepath = server. mappath ("download/aaa.txt"); // path

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 multipart download

Protected void button3_click (Object sender, eventargs E)

{

String filename = "aaa.txt"; // file name saved by the client

String filepath = server. mappath ("download/aaa.txt"); // path

System. Io. fileinfo = new system. Io. fileinfo (filepath );

If (fileinfo. exists = true)

{

Const long chunksize = 102400; // 100 k reads only 100 k each time, which can relieve the pressure on the server

Byte [] buffer = new byte [chunksize];

Response. Clear ();

System. Io. filestream istream = system. Io. file. openread (filepath );

Long datalengthtoread = istream. length; // obtain the total size of the downloaded file

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); // read size

Response. outputstream. Write (buffer, 0, lengthread );

Response. Flush ();

Datalengthtoread = datalengthtoread-lengthread;

}

Response. Close ();

}

}

// Stream download

Protected void button4_click (Object sender, eventargs E)

{

String filename = "aaa.txt"; // file name saved by the client

String filepath = server. mappath ("download/aaa.txt"); // path

// Download an object in the form of a streaming

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 ";

// Notify the browser to download the file instead of opening it

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 ");

// 'File name

Webform. response. addheader ("content-disposition", "attachment; filename = '" + system. web. httputility. urlencode (filenamewhenuserdownload, system. text. encoding. utf8) + "'");

Webform. response. contenttype = "application/octet-stream ";

// 'File content

Webform. response. Write (filebody );//-----------

Webform. response. End ();

}

// The above code downloads a dynamically generated text file. If the file already exists in the server-side object path, you can use the following function:

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 ");

// File name

Webform. response. addheader ("content-disposition", "attachment; filename = '" + system. web. httputility. urlencode (filenamewhenuserdownload, system. text. encoding. utf8) + "'");

Webform. response. contenttype = "application/octet-stream ";

// File Content

Webform. response. Write (system. Io. file. readallbytes (filepath ));//---------

Webform. response. End ();

}

 

 

 

Below is a more detailed 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 ',
'Mfa' => 'application/vnd. mfa ',
'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-ctor ',
'Dir' => 'application/X-ctor ',
'Dxr' => 'application/X-ctor ',
'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 ',
'Textinfo' => 'application/X-textinfo ',
'Text' => 'application/X-textinfo ',
'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 ',
'A' => '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 ',
'Gies' => 'model/iges ',
& Apos; IGES & apos; = & apos; model/IGES & apos ',
'Msh' => 'model/mesh ',
'Mesh '=> 'model/mesh ',
'Silo' => 'model/mesh ',
'Wrl' => 'model/jpa ',
'Jpa' => 'model/jpa ',
'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 ',
'Av' => 'video/X-msvideo ',
'Movi' => 'video/X-SGI-movi ',
'Ice '=> 'x-conference/X-cooltalk'

 

 

 

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.