Asp.net| client's usual file downloads are implemented by jumping out of the window, but there is a problem that will be intercepted by the advertising interception software, and I have a very headache, so look for a better solution. After reading the paper with Response.BinaryWrite, I feel that it is possible.
The following code implements this functionality, resolves the file format problem (that is, only the stream is output, but the file format is not correctly recognized), and the file is read from the registry contenttype
1/**////<summary>
2///Download files
3///</summary>
4///<param name= "filename" > File Physical Address </param>
5 protected void DownloadFile (string filename)
6 {
7
8 String savefilename = "Test.xls";
9 int intstart = filename. LastIndexOf ("\") +1;
Ten savefilename = filename. Substring (Intstart,filename. Length-intstart);
11
System.IO.FileInfo fi=new System.IO.FileInfo (filename);
Fileextname=fi string. Extension;
String default_content_type = "Application/unknown";
RegistryKey Regkey,fileextkey;
String Filecontenttype;
Try
18 {
Regkey=registry.classesroot;
Fileextkey=regkey. OpenSubKey (Fileextname);
Filecontenttype=fileextkey. GetValue ("Content Type", Default_content_type). ToString ();
22}
Catch
24 {
Filecontenttype=default_content_type;
26}
27
28
Response.Clear ();
Response.Charset = "Utf-8";
Response.buffer= true;
this. EnableViewState = false;
response.contentencoding = System.Text.Encoding.UTF8;
34
Response.appendheader ("Content-disposition", "attachment;filename=" + savefilename);
Response.contenttype=filecontenttype;
37
Response.WriteFile (filename);
Response.Flush ();
Response.close ();
41
Response.End ();
43}
The effect chart is as follows: