TransmitFile implementation Download
protected voidButton1_Click (Objectsender, EventArgs e) {Response.ContentType="application/x-zip-compressed"; Response.AddHeader ("content-disposition","Attachment;filename=z.zip"); stringfilename = Server.MapPath ("Download/aaa.zip"); Response.TransmitFile (filename); }
WriteFile Implementation Download
protected voidButton2_Click (Objectsender, EventArgs e) { stringFileName ="Aaa.zip";//file name saved by the client stringFilepath=server.mappath ("Download/aaa.zip");//PathFileInfo FileInfo=NewFileInfo (FilePath); Response.Clear (); Response.clearcontent (); Response.ClearHeaders (); Response.AddHeader ("content-disposition","attachment;filename="+fileName); Response.AddHeader ("Content-length", fileInfo.Length.ToString ()); Response.AddHeader ("content-transfer-encoding","binary"); Response.ContentType="Application/octet-stream"; Response.ContentEncoding= System.Text.Encoding.GetEncoding ("gb2312"); Response.WriteFile (Fileinfo.fullname); Response.Flush (); Response.End (); }
WriteFile Sub-block download
protected voidButton3_Click (Objectsender, EventArgs e) { stringFileName ="Aaa.zip";//file name saved by the client stringFilePath = Server.MapPath ("Download/aaa.zip");//PathSystem.IO.FileInfo FileInfo=NewSystem.IO.FileInfo (FilePath); if(Fileinfo.exists = =true) { Const LongChunkSize =102400;//100K Read the file every time, only read 100K, this can alleviate the pressure of the server byte[] buffer =New byte[ChunkSize]; Response.Clear (); System.IO.FileStream IStream=System.IO.File.OpenRead (FilePath); LongDatalengthtoread = Istream.length;//get the total size of the downloaded fileResponse.ContentType ="Application/octet-stream"; Response.AddHeader ("content-disposition","attachment; Filename="+Httputility.urlencode (fileName)); while(Datalengthtoread >0&&response.isclientconnected) {intLengthread = istream.read (buffer,0, Convert.ToInt32 (ChunkSize));//the size of the readResponse.OutputStream.Write (Buffer,0, Lengthread); Response.Flush (); Datalengthtoread= Datalengthtoread-Lengthread; } response.close (); } }
Stream mode Download
protected voidButton4_Click (Objectsender, EventArgs e) { stringFileName ="Aaa.zip";//file name saved by the client stringFilePath = Server.MapPath ("Download/aaa.zip");//Path//download a file as a stream of charactersFileStream fs =NewFileStream (FilePath, FileMode.Open); byte[] bytes =New byte[(int) fs. Length]; Fs. Read (Bytes,0, Bytes. Length); Fs. Close (); Response.ContentType="Application/octet-stream"; //notifies the browser to download a file instead of opening itResponse.AddHeader ("content-disposition","attachment; Filename="+Httputility.urlencode (FileName, System.Text.Encoding.UTF8)); Response.BinaryWrite (bytes); Response.Flush (); Response.End (); }
Several ways to implement the download function in ASP