In the production of websites, it is often necessary to develop the function of downloading files. There are three ways to download files:
1. ASP download code
<%
filename = Request.QueryString("FileName")
if filename = "" then
Response.Write "Please enter the filename parameter and 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 into an asp type file, and use it like: 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( " The above code will download the server-side a.gif file to the client's c drive without any prompts. It is quite scary without any prompts, but sometimes it is necessary to do this. This code can also be used Run the program on the desktop.
3. ASP NET download code with download prompts
//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 file data
int leng = r.Read(buffer, 0, 1024);
if (leng == 0)//To the end of the file, end
break;
if (leng == 1024)//The read file data length is equal to the buffer length, and the buffer data is written directly
Response.BinaryWrite(buffer);
else
{
//Read file data is smaller than the buffer, redefine the buffer size, only used to read the last data block of the file
byte[] b = new byte[leng];
for (int i = 0; i < leng; i++)
b[i] = buffer[i];
Response.BinaryWrite(b);
}
}
r.Close();//Close the downloaded file
Response.End(); //End file download. This method has a download prompt box, so the server can know when the download is completed.