Implementation of File Upload (C #)

Source: Internet
Author: User
File Upload

First, be sure to set the enctype to "Multipart/form-data" in the form:
<form id= "WEBFORM3" method= "post" enctype= "Multipart/form-data" runat= "Server" >

Two. Determine if there are files uploaded:
When the user does not select any files to upload, that is, when the text box in the HtmlInputFile control is empty, when the upload button is clicked, the File1.PostedFile object obtained at the server is not NULL but has an object, so it cannot be used (file1.postedfile = = NULL) to determine whether the file is uploaded, using (File1.PostedFile.ContentLength!= 0) to judge the better

Three. Determine the type of upload file Mimie:
File upload can use File1.PostedFile.ContentType to read the file Mimie type, this mimie type is the system by uploading file suffix name to obtain.

Four. Save uploaded files:

1. The file can be saved by File1.PostedFile.SaveAs (path)//path is the physical path on the server.

if (File1.PostedFile.ContentLength!= 0)

{

StringBuilder mystr = new StringBuilder ();

Mystr.append ("File name:" + File1.PostedFile.FileName);

Mystr.append ("<br>");

Mystr.append ("File type:" + File1.PostedFile.ContentType);

Mystr.append ("<br>");

Mystr.append ("File length:" + File1.PostedFile.ContentLength.ToString ());

Mystr.append ("<br>");



String path = Server.MapPath ("./"); Current path

String fileName = File1.PostedFile.FileName.Substring (File1.PostedFile.FileName.LastIndexOf ('//') +1);

Path + fileName;

if (file.exists (path) = = True)

{

Label1.Text = "The server already has the file you are uploading:" + fileName;

Return

}

File1.PostedFile.SaveAs (path);



Mystr.append ("Save complete.") ");

Mystr.append ("<br>");

Label1.Text = Mystr.tostring ();

}

Else

{

Label1.Text = "You did not select the file to upload or upload a file length of 0." ";

}


2. The file can also be stored in binary fields of the database through binary reads:
byte[] Filecont = new Byte[file1.postedfile.contentlength];
File1.PostedFile.InputStream.Read (filecont,0, File1.PostedFile.ContentLength);
This byte array filecont is then assigned to the parameters of the binary field of the database, which are written to the database.



File download

A. The server sends the corresponding HTTP Response headers information via Response, and the data of the file to be downloaded to send the file to the client, the HTTP Response headers is shown in the following form in the HTML file:
<meta http-equiv= "Content-type" content= "text/htm" >
The HTTP-EQUIV representation is the name of the headers, and the content represents the value of the headers

Two. First, to output the MIME type of the file:
Page.Response.AddHeader ("Content-type", "MIME type");

Three. Second, to output the downloaded file's open location and file name:
Page.Response.AddHeader ("Content-disposition", "attachment;filename=" + filename);
The Content-disposition HTTP response header allows you to specify the information that the document represents. With this header, you can specify that the document be opened individually (not in a browser), and can be displayed according to the user's actions. If the user wants to save the document, you can also suggest a file name for the document. This suggestion name appears in the file Name column of the Save as dialog box.
Open Location:
Attachment―― is sent to the client as an attachment, and the client opens the file separately.
Inline―― indicates that the file will be opened in the browser.
Filename:
Filename―― represents the file name sent to the client file.

Four. Prepare the file data to be sent to the client:

1. The data from different types of sources is first converted to a byte type array and then sent to the client via the Response.BinaryWrite method:

1.1. Read the file to get the byte array: string FileName; Build or get the filename to send to the client

String filePath = Server.MapPath ("./") + FileName; Suppose the file is in the current directory

if (file.exists (filePath) = = False)

{

This file is not on the server

Return

}

FileStream myFile = File.openread (FilePath); Read files into FileStream

byte[] Filecont = new Byte[myfile.length];

Myfile.read (filecont,0, (int) myfile.length); Convert the contents of a file stream into a byte array


1.2. Read in the binary field of the database://Get the ID of the picture from the URL

String imageID = request.querystring["img"];

Building query Statements

String sqltext = "Select Img_data, Img_contenttype from Image WHERE img_pk =" + imageID;

SqlConnection connection = new SqlConnection (configurationsettings.appsettings["DSN"). ToString ());

SqlCommand command = new SqlCommand (sqltext, connection);

Connection. Open ();

SqlDataReader dr = command. ExecuteReader ();

if (Dr. Read ())

{

Byte[] Filecont = (byte[]) dr["Img_data"];

}

Connection. Close ();


1.3. read files from the Internet: HttpWebRequest mywebrequest = (HttpWebRequest) webrequest.create ("Http://www.via.com/aa.xls");

HttpWebResponse mywebresponse = (HttpWebResponse) mywebrequest.getresponse ();

Stream Readstream = Mywebresponse.getresponsestream ();



byte[] bytes = new Byte[readstream.length];

bytes = Readstream.read (bytes,0,readstream.length);


The byte array of the contents of the file obtained by the above three methods can be used for output:
Page.Response.BinaryWrite (Filecont);

Page.Response.End ();



2. Direct read file output: string FileName; Build or get the filename to send to the client

String filePath = Server.MapPath ("./") + FileName; Suppose the file is in the current directory

if (file.exists (filePath) = = False)

{

This file is not on the server

Return

}

Page.Response.Clear ();

Page.Response.AddHeader ("Content-type", "image/gif"); Depending on the MIME's different settings

Page.Response.AddHeader ("Content-disposition", "inline;filename=" + FilePath);

Page.Response.WriteFile (FilePath);

Page.Response.End ();



End of content//
Related Article

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.