ASP. NET page download Program Http://tech.163.com/09:22:47 Source: aspcool comments 0 Forum
You often need to develop the file download function during website creation. The following three methods are available to download files:
1. Download with ASP Code
<%
Filename = request. querystring ("FILENAME ")
If filename = "" then
Response. Write "Enter the filename parameter to specify the downloaded file name"
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. The usage is similar to: Download. asp? Filename=a.gif.
2. Use WebClient
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 code above downloads the C drive of the client without any prompts from the.gif file on the server side. It is terrible if there are no prompts, but sometimes it is necessary to do so. This code can also run on the desktop.
3. asp net download code with the download prompt
// Open the object to be downloaded
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)
{< br> // open a buffer space
byte [] buffer = new byte [1024];
// read file data
int Leng = R. read (buffer, 0, 1024);
If (Leng = 0) // end at the end of the file
break;
If (Leng = 1024) // The length of the read file is equal to the length of the buffer, and the buffer data is directly written into
response. binarywrite (buffer);
else
{< br> // read the file data is smaller than the buffer, and the buffer size is redefined, only used to read the last data block of the file
byte [] B = new byte [Leng];
for (INT I = 0; I B [I] = buffer [I];
response. binarywrite (B);
}< BR >}< br> r. close (); // close the download file
response. end (); // end File Download
This method has a download prompt box, and the server can know when the download is complete.