asp.net implementation of File download code _ Practical Skills

Source: Internet
Author: User
Tags flush httpcontext rar knowledge base
Copy Code code as follows:

public partial class FileDownLoad:System.Web.UI.Page
{
Provide downloaded files, not encoded words file name will be garbled
private string fileName = HttpContext.Current.Server.UrlEncode ("spec. rar");
private string FilePath = HttpContext.Current.Server.MapPath ("spec. rar");
Downloading files using Transmiffile
protected void Btndl1_click (object sender, EventArgs e)
{
FileInfo info = new FileInfo (FilePath);
Long fileSize = info. Length;
Response.Clear ();
Response.ContentType = "application/x-zip-compressed";
Response.AddHeader ("Content-disposition", "attachment;filename=" + filename);
Do not indicate content-length use flush will not show download progress
Response.AddHeader ("Content-length", filesize.tostring ());
Response.TransmitFile (FilePath, 0, fileSize);
Response.Flush ();
Response.close ();
}

Downloading files using WriteFile
protected void Btndl2_click (object sender, EventArgs e)
{
FileInfo info = new FileInfo (FilePath);
Long fileSize = info. Length;
Response.Clear ();
Response.ContentType = "Application/octet-stream";
Response.AddHeader ("Content-disposition", "attachement;filename=" + filename);
Specify File size
Response.AddHeader ("Content-length", filesize.tostring ());
Response.WriteFile (FilePath, 0, fileSize);
Response.Flush ();
Response.close ();
}

To download a file using Outputstream.write chunking
protected void Btndl3_click (object sender, EventArgs e)
{
Specify block size
Long chunksize = 102400;
Create a buffer of 100K
byte[] buffer = new Byte[chunksize];
Number of bytes read
Long dataToRead = 0;
FileStream stream = null;
Try
{
Open File
stream = new FileStream (FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
dataToRead = stream. Length;

Add HTTP Headers
Response.ContentType = "Application/octet-stream";
Response.AddHeader ("Content-disposition", "attachement;filename=" + filename);
Response.AddHeader ("Content-length", datatoread.tostring ());

while (dataToRead > 0)
{
if (response.isclientconnected)
{
int length = stream. Read (buffer, 0, Convert.ToInt32 (chunksize));
Response.OutputStream.Write (buffer, 0, length);
Response.Flush ();
Response.Clear ();
dataToRead = length;
}
Else
{
Prevent client from losing connection
dataToRead =-1;
}
}
}
catch (Exception ex)
{
Response.Write ("Error:" + ex.) message);
}
Finally
{
if (stream!= null)
{
Stream. Close ();
}
Response.close ();
}
}

Use BinaryWrite to download files, large file efficiency not
protected void Btndl4_click (object sender, EventArgs e)
{
FileStream stream = null;
Try
{
Read a file, read a large file, join a large amount of memory
stream = new FileStream (FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] bytes = new Byte[stream. Length];
Stream. Read (bytes, 0, bytes. Length);
Stream. Close ();

Add HTTP Headers
Response.ContentType = "Application/octet-stream";
Response.AddHeader ("Content-disposition", "attachement;filename=" + filename);
Response.AddHeader ("Content-length", bytes. Length.tostring ());
Response.BinaryWrite (bytes);
Response.Flush ();
}
catch (Exception ex)
{
Response.Write ("Error:" + ex.) message);
}
Finally
{
if (stream!= null)
{
Stream. Close ();
}
Response.close ();
}
}
To download a file using BinaryWrite chunking
protected void Btndl5_click (object sender, EventArgs e)
{
Specify blocks and buffers
Long chunksize = 102400;
byte[] buffer = new Byte[chunksize];
FileStream stream = null;
Long dataToRead = 0;
Try
{
stream = new FileStream (FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
dataToRead = stream. Length;
Add HTTP Headers
Response.ContentType = "Application/octet-stream";
Response.AddHeader ("Content-disposition", "attachement;filename=" + filename);
Response.AddHeader ("Content-length", datatoread.tostring ());

while (dataToRead > 0)
{
if (response.isclientconnected)
{
int length = stream. Read (buffer, 0, Convert.ToInt32 (chunksize));
Response.BinaryWrite (buffer);
Response.Flush ();
Response.Clear ();

dataToRead = length;
}
Else
{
dataToRead =-1;
}
}

}
catch (Exception ex)
{
Response.Write ("Error:" + ex.) message);
}
Finally
{
if (stream!= null)
{
Stream. Close ();
}
Response.close ();
}
}
}

Above all except the fourth kind does not recommend, other all can, but the personal feeling blocks the download better. No careful testing, so there may be a problem.

Note: The Chinese file name to be encoded to correctly display. For long Chinese file name (UTF8 encoding more than 153 bytes of Chinese) even if the code, there is a problem, you can refer to the following article.

regarding the Chinese file downloading question, the on-line consultation and the answer questions already many, I originally processing downloads the code as follows:

Response.setheader ("Content-disposition", "attachment; Filename= "+ java.net.URLEncoder.encode (fileName," UTF-8 "));
Download the program has this sentence, generally in the IE6 download prompt box will correctly display the name of the file, whether it is Simplified Chinese, or Japanese. But did not carefully test the name of a very long filename in Chinese. Now after careful testing, found that the text as long as more than 17 words, you can not download. After a good Google and repeated testing, it is finally a systematic understanding of the problem, as follows:

I. Through my original way, that is, first with Urlencoder encoding, when the Chinese text more than 17, IE6 can not download files. This is the bug of IE, see Microsoft Knowledge Base article KB816868. The reason may be that the length of the header is limited to about 150 bytes when IE handles the Response header. and a encoding into UTF-8 is 9 bytes, then 17 words is 153 bytes, so it will be an error. Microsoft has provided a patch that can be downloaded from here. This patch needs to be installed IE6 SP1 first. Because I usually play the patch, my IE6 version number is 6.0.2800.1106.xpsp2_xxxxx. So I may have installed the patch so that it can be downloaded, but still the file name is truncated. Microsoft lets us wait for IE to release the next service pack. I also saw the good news on the internet today, under the pressure of Firefox, IE7 may release in the year. In addition, Firefox does not support such a way that the encoded%XX%XX will be displayed directly as a filename.


Two. I try to use the JavaMail Mimeutility.encode () method to encode the filename, which is encoded as =?gb2312? b?xxxxxxxx?= this form, and find the corresponding standard support from the RFC1522. Unfortunately, IE6 does not support this standard. I tried it, and Firefox was supported.

Three. A solution offered by many people on the Web: encoding file names into iso8859-1 appears to be a valid solution, with the following code:

Response.setheader ("Content-disposition", "attachment;filename=" + New String (Filename.getbytes ("gb2312"), " Iso8859-1 "));

In the case of ensuring that the attachment file name is in simplified text, then this method is indeed the most effective, do not allow customers to upgrade the IE. If Taiwan compatriots use, change gb2312 to Big5 on the line. But now the system is usually joined by the internationalization of support, universal use of UTF-8. If there is a simplified Chinese text in the file name, there is also traditional English, and Japanese. Then the garbled is produced. In addition, on my Computer Firefox (v1.0-en) download is garbled.

Compromise, I combined the one or three way, the code snippet is as follows:
Copy Code code as follows:

String fileName = Urlencoder.encode (Atta.getfilename (), "UTF-8");
/*
* http://support.microsoft.com/default.aspx?kbid=816868
*/
if (Filename.length () > 150) {
String guesscharset = xxxx/* The possible encoding is derived from the locale of request, and the Chinese operating system is usually gb2312*/
FileName = new String (Atta.getfilename (). GetBytes (Guesscharset), "iso8859-1");
}
Response.setheader ("Content-disposition", "attachment; Filename= "+ fileName);

Firefox is not considered because it currently does not seem to have a strong intrusion into IE's corporate user market. It is often the progress, not the compatibility, that affects the customer's pay.
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.