asp.net directly save files to client

Source: Internet
Author: User

In the process of writing our system, there should be a lot of times when customers need to download files. My first practice (should also be the practice of most people?) Is:

1 HttpResponse response = HttpContext.Current.Response;

2 string js = "<script language=javascript>window.open (' {0} ');</script>";

3 js = string. Format (JS, url);

4 response. Write (JS);

5

But there is a problem, that is, the ad interception software will be directly intercepted, and I have a very headache, so to find a better solution. After reading the text with Response.BinaryWrite, I think it's OK to do so, modify the code as follows:

1/**//**//**////<summary>
2/**////download file
3/**////</summary>
4/**////<param name= "FileName" > File Physical Address </param>
5
6protected void DownloadFile (string filename)
7 ... {
8 string savefilename = ' Test.xls ';
9 int intstart = filename. LastIndexOf ("\") +1;
Ten savefilename = filename. Substring (Intstart,filename. Length-intstart);
One FileStream myFileStream;
Long FileSize;

myFileStream = new FileStream (filename,filemode.open);
FileSize = myfilestream.length;

17 byte[] Buffer = new byte[(int) FileSize];
Myfilestream.read (Buffer, 0, (int) FileSize);
Myfilestream.close ();

Response.AddHeader ("Content-disposition", "attachment;filename=" +savefilename);
22 response.contentencoding = System.Text.Encoding.GetEncoding ("GB2312");
Response.ContentType = "application/vnd.ms-excel";
Response.BinaryWrite
(Buffer),
Response.Flush (),
RespoNse. Close ();
Response.End ();

}

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.