Asp.net| Program | download | page
In the production of the site often need to develop the function of downloading files, the following three ways to download the file:
1, ASP implementation of the download code
<%
filename = request.querystring ("filename")
if filename = "" Then
Response.Write "Please enter filename parameter, specify download filename"
Else
Response.ContentType = "Application/octet-stream"
Response.AddHeader "Content-disposition", "attachment"; filename = "& filename
Set FileStream = Server.CreateObject ("ADODB.stream")
Filestream.mode = 3
Filestream.type = 1
Filestream.open
Filestream.loadfromfile (Server.MapPath (filename))
Response.BinaryWrite (FileStream.Read)
filestream.close ()
Set FileStream = Nothing
End If
%> Save the above code as an ASP-type file that is similar when used: Download.asp?filename=a.gif.
2, use WebClient
to add the following code to the Download button event
System.Net.WebClient WC = new System.Net.WebClient ();
WC. DownloadFile ("http://localhost/a.gif ", "c:\a.gif");
The above code will put the server-side a.gif file to download without any hint of the client's C disk, without any hint or more frightening, but sometimes it is really necessary to do so. The code can also be run on a desktop program.
3, ASP net download code with download hint
//Open the file to download
System.IO.FileStream r = new System.IO.FileStream (FileName, System.IO.FileMode.Open);
//Set basic information
Response.Buffer = false;
Response.AddHeader ("Connection", "keep-alive");
Response.ContentType = "Application/octet-stream";
Response.AddHeader ("Content-disposition", "attachment;filename=" + System.IO.Path.GetFilEname (FileName));
Response.AddHeader ("Content-length", r.length.tostring ());
while (true)
{
//Open buffer space
byte[] buffer = new byte[1024];
//Read the file data
int leng = r.read (buffer, 0, 1024);
if (leng = = 0)//To end of file, ending
break;
if (leng = = 1024)//read out file data length equals buffer length, write buffer data directly to
Response.BinaryWrite (buffer);
Else
{
//read out file data is smaller than the buffer, redefine the buffer size, only to read the last block of data in the file
byte[] b = new Byte[leng];
for (int i = 0; i < Leng; i++)
B[i] = buffer[i];
Response.BinaryWrite (b);
}
}
r.close ()//close Download file
Response.End ()//end File Download
This method has the download prompt box, the server side may know when the download completes.