HTML Markup
<div> <div> 1. Upload Web control FileUpload to Web site root "FileUpload1"runat="Server"/> <asp:button id="Btnupload"runat="Server"text="Upload"onclick="Btnupload_click"/> <asp:label id="Label1"runat="Server"text=""style="color:red"></asp:Label> </div> "color:red"/> <div> 2. Upload to Web site root "File1"Type="file"runat="Server"/> <asp:button id="Btnhtmlfileupload"runat="Server"text="Upload"onclick="Btnhtmlfileupload_click"/> <asp:label id="Label2"runat="Server"text=""style="color:red"></asp:Label> </div> "color:red"/> <div> 3. <input type= with HTML elements"file"/> upload to the web site root by request.files. "File2"Type="file"Name="file"/> <asp:button id="btnhtmlupload_request"runat="Server"text="Upload"onclick="Btnhtmlupload_request_click"/> <asp:label id="Label3"runat="Server"text=""style="color:red"></asp:Label> </div> </div>
View Code
The code behind page
//method One: Use the FileUpload control to upload files protected voidBtnupload_click (Objectsender, EventArgs e) { if(fileupload1.hasfile) {Fileupload1.saveas (Server.MapPath ("~/saveuploadfiles/") +fileupload1.filename); Label1.Text="Upload Success! "; } } //method Two: Upload the file using the HTML file Upload control protected voidBtnhtmlfileupload_click (Objectsender, EventArgs e) { if(File1.PostedFile.ContentLength >0) {File1.PostedFile.SaveAs (Server.MapPath ("~/saveuploadfiles/") +Path.getfilename (File1.PostedFile.FileName)); Label2.Text="Upload Success! "; } } //method Three: Use HTML element <input type= "file" .../>, upload to Web site root by request.files. protected voidBtnhtmlupload_request_click (Objectsender, EventArgs e) { if(request.files["file"]. ContentLength >0) {request.files["file"]. SaveAs (Server.MapPath ("~/saveuploadfiles/") + Path.getfilename (request.files["file"]. FileName)); Label3.text="Upload Success! "; } }View Code
--note the difference between two points:
One: Fileupload.filename gets the client upload file name (without path), while File1.PostedFile.FileName and request.files["file"]. FileName is different in different browsers: IE8 is the full qualified name of the client upload file (with path), Google, Apple and other browsers are still the file name (without path).
Two: FileUpload control has HasFile property, used to determine whether the user chose to upload the file, and the following two methods need to determine the upload file size ContentLength property, when the user did not choose to upload the file, the property value is 0.
Three ways to upload files