In Web programming, we often need to upload some local files to the Web server. After uploading, users can easily browse these files through a browser, which is widely used.
So how does C # implement the file upload function? The following is a brief introduction.
First, add a web Form for uploading in your Visual C # Web project. to upload files,
You need to select the File Field control of the HTML class in the ToolBox and add the control to the Web Form. However, this control is not a server control yet. We need to add the following code to it: <input id = uploadfile1 type = file size = 49 runat = "server"> in this way, it becomes a server control. If you need to upload multiple files at the same time, we can add this control accordingly.
Note that the <form> attribute must be set:
<Form method = post encType = multipart/form-data runat = "server"> if this attribute is not available, upload cannot be implemented.
Then add a Button of the Web Form class to the Web Form, and double-click the Button to add the following code:
// Program segment for uploading images
DateTime now = DateTime. Now;
// Get the current time to the object now of the DataTime class
String strBaseLocation = "D: webFCpic ";
// This is the absolute directory of the server to which the file will be uploaded
If (uploadfile1.PostedFile. ContentLength! = 0) // determine whether the selected file length is 0
{Uploadfile1.PostedFile. SaveAs (strBaseLocation + now. DayOfYear. ToString () + uploadfile1.PostedFile. ContentLength. ToString () + ". jpg ");
// Execute the upload and automatically name the File Based on the date and file size to ensure that the file is not repeated.
Label1.Text = "Image 1 has been uploaded. The file name is:" + now. DayOfYear. ToString () + uploadfile1.PostedFile. ContentLength. ToString () + ". jpg ";
Navigator. Insert (System. Xml. TreePosition. After, XmlNodeType. Element, "pic1 ","","");
Navigator. Insert (System. Xml. TreePosition. FirstChild, XmlNodeType. Text, "pic1 ","","");