Asp.net directly saves (downloads) the file to the client

Source: Internet
Author: User
In the compilation process of our system, there should be many times when users need to download files. My first practice (should it be the practice of most people ?) Yes:

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

But there is a problem, that is, it will be directly intercepted by the ad interception software. In addition, I am very headache, so I am looking for a better solution. I used Response. after writing a file stream to BinaryWrite, I think this can be done. The modification code is as follows:

1/** // <summary>
2/*** // download the object
3/** // </summary>
4/** // <param name = "filename"> physical address of the file </param>
5
6 protected void DownloadFile (string filename)
7 ...{
8 string saveFileName = "test.xls ";
9 int intStart = filename. LastIndexOf ("\") + 1;
10 saveFileName = filename. Substring (intStart, filename. Length-intStart );
11 FileStream MyFileStream;
12 long FileSize;
13
14 MyFileStream = new FileStream (filename, FileMode. Open );
15 FileSize = MyFileStream. Length;
16
17 byte [] Buffer = new byte [(int) FileSize];
18 MyFileStream. Read (Buffer, 0, (int) FileSize );
19 MyFileStream. Close ();
20
21 Response. AddHeader ("Content-Disposition", "attachment; filename =" + saveFileName );
22 Response. ContentEncoding = System. Text. Encoding. GetEncoding ("GB2312 ");
23 Response. ContentType = "application/vnd. ms-excel ";
24
25 Response. BinaryWrite (Buffer );
26 Response. Flush ();
27 Response. Close ();
28 Response. End ();
29
30}

But there is a serious problem, that is, the file format. In this way, the stream is output and the format cannot be correctly recognized. Fortunately, there are endless possibilities. Yuzu Nan proposed the idea of directly displaying files to the browser (Response) without considering the file type, so I hurriedly studied the idea of grapefruit Nan and modified the final code:

1/** // <summary>
2/*** // download the object
3/** // </summary>
4/** // <param name = "filename"> physical address of the file </param>
5 protected void DownloadFile (string filename)
6 ...{
7 string saveFileName = "test.xls ";
8 int intStart = filename. LastIndexOf ("\") + 1;
9 saveFileName = filename. Substring (intStart, filename. Length-intStart );
10
11 Response. Clear ();
12 Response. Charset = "UTF-8 ";
13 Response. Buffer = true;
14 this. EnableViewState = false;
15 Response. ContentEncoding = System. Text. Encoding. UTF8;
16
17 Response. AppendHeader ("Content-Disposition", "attachment; filename =" + saveFileName );
18 Response. WriteFile (filename );
19 Response. Flush ();
20 Response. Close ();
21
22 Response. End ();
23}

I used Asp.net yesterday to directly save the file to the client. After repeated tests, all kinds of documents run completely normally. So I modified the existing code last night and modified the Download Method to Solve the window interception problem that had been plagued by me.

I was complacent in the morning, so I don't need to explain to the customer why the window is gone. Unfortunately, people are not as good as days.

In the morning, the customer reported that all downloaded files were garbled. Test on the local machine immediately. No problem. It's okay to try it on a colleague's machine.

That should be the problem with the client. We had to ask the customer NetMeeting to demonstrate her operation process. Download-> Save-> open. Isn't this simple process wrong?

When I was depressed, my mind suddenly flashed and finally found something different. I tried it right away!

What is the difference? See the operation diagram:
Guest operation diagram
My operation diagram
Should you see the difference? Still unable to see?
The culprit of this incident is:



Solution: How to Use lovecherry to read the file ContentType from the Registry

Corrected code:
1/** // <summary>
2 // download an object
3 /// </summary>
4 /// <param name = "filename"> physical file address </param>
5 protected void DownloadFile (string filename)
6 {
7
8 string saveFileName = "test.xls ";
9 int intStart = filename. LastIndexOf ("\") + 1;
10 saveFileName = filename. Substring (intStart, filename. Length-intStart );
11
12 System. IO. FileInfo fi = new System. IO. FileInfo (filename );
13 string fileextname = fi. Extension;
14 string DEFAULT_CONTENT_TYPE = "application/unknown ";
15 RegistryKey regkey, fileextkey;
16 string filecontenttype;
17 try
18 {
19 regkey = Registry. ClassesRoot;
20 fileextkey = regkey. OpenSubKey (fileextname );
21 filecontenttype = fileextkey. GetValue ("Content Type", DEFAULT_CONTENT_TYPE). ToString ();
22}
23 catch
24 {
25 filecontenttype = DEFAULT_CONTENT_TYPE;
26}
27
28
29 Response. Clear ();
30 Response. Charset = "UTF-8 ";
31 Response. Buffer = true;
32 this. EnableViewState = false;
33 Response. ContentEncoding = System. Text. Encoding. UTF8;
34
35 Response. AppendHeader ("Content-Disposition", "attachment; filename =" + saveFileName );
36 Response. ContentType = filecontenttype;
37
38 Response. WriteFile (filename );
39 Response. Flush ();
40 Response. Close ();
41
42 Response. End ();
43}

Finally, it is concluded that there is a way to directly display the file to the browser (Response) without considering the file type, so that the client does not hide the known extension, however, this method cannot adapt to most computer users (usually only those familiar with computers will do this ?)

The bbs method has not been tried yet. I don't know if it works.

Private Sub Page_Load (ByVal sender As System. Object, ByVal e As System. EventArgs )_
Handles MyBase. Load
'User code to place the initialization page here
'Determine whether the database is an SQL Server database. Here it is False.
Dim blnIsSQLServer As System. Boolean = False
Dim strSQL As String
Dim objDataset As New DataSet ()
Dim objConn As Object
Dim strCnn As String

If blnIsSQLServer Then
StrCnn = "User ID = sa; Initial Catalog = Northwind; Data Source =. \ NetSDK ;"
ObjConn = New System. Data. SqlClient. SqlConnection (strCnn)
ObjConn. Open ()
Dim objAdapter As New System. Data. SqlClient. SqlDataAdapter ()
StrSQL = "Select * from MERs where country = 'usa '"
ObjAdapter. SelectCommand = New System. Data. SqlClient. SqlCommand (strSQL, objConn)
ObjAdapter. Fill (objDataset)
Else
StrCnn = "Provider = Microsoft. Jet. OLEDB.4.0; Data Source =" + Server. MapPath ("Test. mdb ")
ObjConn = New System. Data. OleDb. OleDbConnection (strCnn)
ObjConn. Open ()
Dim objAdapter As New System. Data. OleDb. OleDbDataAdapter ()
StrSQL = "Select Top 10 Title From Document"
ObjAdapter. SelectCommand = New System. Data. OleDb. OleDbCommand (strSQL, objConn)
ObjAdapter. Fill (objDataset)
End If
Dim oView As New DataView (objDataset. Tables (0 ))
DataGrid1.DataSource = oView
DataGrid1.DataBind ()
ObjConn. Close ()
ObjConn. Dispose ()
ObjConn = Nothing
If Request. QueryString ("bExcel") = "1" Then
Response. ContentType = "application/vnd. ms-excel"
'Remove charset settings from the Content-Type header
Response. Charset = ""

'Close ViewState
Me. EnableViewState = False
Dim tw As New System. IO. StringWriter ()
Dim hw As New System. Web. UI. HtmlTextWriter (tw)
'Get control HTML
DataGrid1.RenderControl (hw)
'Write HTML back to the browser
Response. Write (tw. ToString ())
Response. End ()
End If
End Sub
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.