In a web project, a file on the server needs to be downloaded to the client.CodeSimple: directly paste the code
/// <Summary>
/// How to download and view files
/// </Summary>
/// <Param name = "fileserverurl"> File relative path (Virtual Path uploaded to the server ). E: \ User \ AA \ a.doc </Param>
/// <Param name = "page"> Page name </Param>
/// <Returns> Returns true if the object is successfully downloaded; otherwise, returns flase. </Returns>
Public Bool Filesdownload ( String Fileserverurl, system. Web. UI. Page)
{
Try
{
String Fileserverpath = Page. server. mappath (fileserverurl );
System. Io. fileinfo fi = New System. Io. fileinfo (fileserverpath );
Fi. Attributes = System. Io. fileattributes. normal;
System. Io. filestream = New System. Io. filestream (fileserverpath, system. Io. filemode. Open );
Long Filesize = Filestream. length;
Int I = Convert. toint32 (filesize );
Page. response. contenttype = " Application/octet-stream " ;
Page. response. addheader ( " Content-Disposition " , " Attachment; filename = " + System. Web. httputility. urlencode (fileserverpath, system. Text. encoding. utf8 ));
Page. response. addheader ( " Content-Length " , Filesize. tostring ());
Byte [] Filebuffer = New Byte [I];
Filestream. Read (filebuffer, 0 , I );
Filestream. Close ();
Page. response. binarywrite (filebuffer );
Page. response. Buffer = True ;
Page. response. Flush ();
// Page. response. Clear ();
Page. response. Close ();
Page. response. End ();
Return True ;
}
Catch
{
Return False ;
}
}
When using page. response. before flush (), add page. response. buffer = true indicates buffering the output content and executing the page. response. when flush () is used, the content will be sent to the client after all the content is buffered. In this way, no error occurs, causing the page to become stuck, so that the user can wait without limit.Page. response. Buffer= TrueAnd page. response. Flush. OtherwisePage. response. Flush ()An error is reported. In addition, the page. response. Clear () clause is commented out, indicating that the content in the buffer will not be cleared.When a user downloads a file on the same page multiple times, he directly reads the file from the cache, downloads it to the client, and removes this sentence. When the file is requested for the second or third time, the page is stuck.