Asp. NET file upload Download (2) Go

Source: Internet
Author: User
Tags urlencode

ASP. NET upload, download file

2011-01-08 16:21:48|  Category:. NET | Tags: | Report | Font size Big medium small subscription

First we want to determine whether the user chooses to upload the file, we can use the following sentence to achieve:
if (file1.postedfile.contentlength>0)
If the user has uploaded files, then:
String name = File1.PostedFile.FileName;//Gets the input file name
int i= name. LastIndexOf (".");
String NewName =name. Substring (i);//Gets the file name extension
Change the "c:\\" below to the address you want to save.
DateTime Now=datetime.now;
String Strname=now. Year.tostring () +now. Month.tostring () +now. Day.tostring () +file1.postedfile.contentlength.tostring () +newname;//renames the file. The name is: Year + month + day + file size.

Common ways to download files in ASP (GO)

1. Stream mode download     protected void Button4_Click (object sender, EventArgs e)     {        string filename = "Aaa.txt";//client-saved file name   & nbsp;     string filePath = Server.MapPath ("Download/aaa.txt");//path

Download the file as a stream of characters FileStream fs = new FileStream (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 the file instead of opening Response.AddHeader ("Content-disposition", "attachment;         Filename= "+ httputility.urlencode (FileName, System.Text.Encoding.UTF8));         Response.BinaryWrite (bytes);         Response.Flush (); Response.End ();

}

2.WriteFile chunked download protected void button3_click (object sender, EventArgs e) {

string filename = "Aaa.txt";//client-saved file name string FilePath = Server.MapPath ("Download/aaa.txt");//path

System.IO.FileInfo FileInfo = new System.IO.FileInfo (FilePath);

if (fileinfo.exists = = true) {Const LONG ChunkSize = 102400;//100k reads the file every time, only 100K is read, which can relieve the pressure on the server byte[] buffer = new Byte[chunksize];

            Response.Clear ();             System.IO.FileStream IStream = System.IO.File.OpenRead (FilePath);             Long datalengthtoread = istream.length;// Get the total size of the downloaded file             Response.ContentType = "application/ Octet-stream ";             Response.AddHeader ("Content-disposition", " Attachment Filename= "+ httputility.urlencode (fileName));             while (Datalengthtoread > 0 && response.isclientconnected)             {                 int lengthread = Istream.read ( Buffer, 0, Convert.ToInt32 (ChunkSize));//The size of the read                 Response.OutputStream.Write (buffer, 0, lengthread);                 Response.Flush ();                 Datalengthtoread = Datalengthtoread-lengthread;            }              Response.close ();        }    }

3.WriteFile implementation download protected void button2_click (object sender, EventArgs e) {/* using System.IO; */

string filename = "Asd.txt";//client-saved file name string FilePath = Server.MapPath ("Download/aaa.txt");//path

        FileInfo FileInfo = new FileInfo (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 ();    }

   4.TransmitFile Implementation download          protected void Button1_click1 ( Object sender, EventArgs e)         {            /*              Microsoft provides a new approach to response objects TransmitFile to address the use of Response.BinaryWrite               downloading more than 400MB files causes the Aspnet_wp.exe process to recycle without successfully downloading the issue. The              code is as follows:               */            String strFileName = "Three idle device management system operating manual iems.ppt";             Response.ContentType = "application/ X-zip-compressed ";            //response.contentencoding = System.teXt. Encoding.GetEncoding ("gb2312");             string filename = BLL. Config.part_em_upload_doc + strFileName;

Bll. Config.part_em_upload_doc is the path ("d:/emuploaddoc/") Response.AddHeader ("Content-disposition", "Attachment;fil Ename= "+server.urlpathencode (strFileName));

server.urlpathencode () resolves the file name garbled problem.         Response.TransmitFile (filename); }

Upload a File instance:

if (Fileupload.PostedFile.ContentLength > 0)    //Determine if the user uploaded the file                  {                     String strFileName = fileupload.postedfile.filename; //Get upload path and file name                      int i = strFileName. IndexOf (".");

   //if (! System.IO.Directory.Exists (path)) directory.createdirectory (path); Determine if there are no uploaded directories and create this directory                      string strnewname = strFileName. Substring (i); Gets the extension of the uploaded file                      datetime dttime = new DateTime ();                      string struploadname = Fileupload.filename; Get file names for uploaded files                     //string struploadname = DateTime.Now.ToString ("Yyyymmddhhmmss")                     //              + Fileupload.postedfilE.contentlength.tostring () + strnewname;  //rename the file. Name: Year + month + day + file size                      String Path = Server.MapPath ("~/fileupload/receptiondatabase/");  //Get server folder                      String FileURL = path + "\ \" + Struploadname;                      Fileupload.PostedFile.SaveAs (FileURL);   //upload file to server                      Resources. UploadFile = struploadname;  //attachment file name

}

Download the file instance:

The using System.IO is referenced first;

if (!string. IsNullOrEmpty (this. FileName)//To determine if there is an attachment, read the attachment name from the repository filename to indicate the attachment name {string filename = this.                 FileName;                 string filepath = "~/fileupload/receptiondatabase/" + filename;  String path = Server.MapPath (filepath); Get file path

                FileStream fs = new FileStream (path, FileMode.Open);                 byte[] bytes = new byte[ (int) fs. Length];                 FS. Read (bytes, 0, bytes. Length);                 FS. Close ();                 Response.ContentType = "Application/octet-stream";                //Notification browser download file is not open file                 Response.AddHeader (" Content-disposition "," attachment; Filename= "+ httputility.urlencode (filename, System.Text.Encoding.UTF8));                 response.transmitfile (path);                 Response.BinaryWrite (bytes);                 Response.Flush ();                 Response.End ();

      //test can not download software (thunderbolt, etc.) Download parts             }             else             {                 this. Clientscriptalert ("This item has no attachments!") ");            }              this. FileName = "";

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.