Asp. NET relies on the. NET Framework class library, encapsulating a large number of features, making uploading files very simple, mainly has the following three basic methods.
Method One: Upload the Web control fileupload to the Web site root directory.
<form id= "Form1" runat= "Server" >
<asp:fileupload id= "FileUpload1" runat= "Server"/>
<asp:button id= "Button1" runat= "server" text= "upload" onclick= "Button1_Click"/>
<asp:label id= "Label1" runat= "Server" text= "style=" color:red "></asp:Label>
</form>protected void Button1_Click (object sender, EventArgs e)
{
if (fileupload1.hasfile)
{
Fileupload1.saveas (Server.MapPath ("~/") + Fileupload1.filename);
Label1.Text = "Upload succeeded!" ";
}
}
Method Two: Use HTML control HtmlInputFile to upload to the Web site root directory.
<form id= "Form1" runat= "Server" >
<input type= "File" id= "File1" runat= "Server"/>
<asp:button id= "Button1" runat= "server" text= "upload" onclick= "Button1_Click"/>
<asp:label id= "Label1" runat= "Server" text= "style=" color:red "></asp:Label>
</form>protected void Button1_Click (object sender, EventArgs e)
{
if (File1. Postedfile.contentlength > 0)
{
File1. Postedfile.saveas (Server.MapPath ("~/") + Path.getfilename (file1. Postedfile.filename));
Label1.Text = "Upload succeeded!" ";
}
}
Method Three: Use HTML element <input type= "file" .../>, upload to Web site root by request.files.
<form id= "Form1" runat= "Server" enctype= "Multipart/form-data" >
<input type= "File" name= "file"/>
<asp:button id= "Button1" runat= "server" text= "upload" onclick= "Button1_Click"/>
<asp:label id= "Label1" runat= "Server" text= "style=" color:red "></asp:Label>
</form>protected void Button1_Click (object sender, EventArgs e)
{
if (request.files["file"]. ContentLength > 0)
{
request.files["File"]. SaveAs (Server.MapPath ("~/") + path.getfilename (request.files["file"]. FileName));
Label1.Text = "Upload succeeded!" ";
}
}
Note Two differences:
One,fileupload.filename get the client upload file name (without path), and 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).
Second, theFileUpload control has the HasFile property, is 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 value of this property is 0. It can be seen that the FileUpload package is higher, but the flexibility is slightly worse.
Asp. NET file upload three basic methods