Home > Getting Started > ASP.NET Syntax > ASP.NET Syntax for HTML Controls > HtmlInputFile
ASP.NET Syntax ASP.NET Syntax for HTML Controls
Creates a file upload control.
Declarative Syntax
<input type = file id="accessID" runat="server"
accept = "MIMEencodings"
maxlength = "maxfilepathlength"
postedfile = "uploadedfile"
size = "widthoffilepathtextbox"
>
For information on the individual members of this class, see HtmlInputFile in the class library.
- This control does not require an end tag.
The HtmlInputFile control enables programming of the HTML <input type=file
> element. With this control, you can allow the upload of binary or text files from a client browser to the server. File upload is enabled in all HTML 3.2 and later Web browsers.
Developers can use the HtmlInputFile control to easily design a page that allows users to upload a file to a designated directory on a Web server.
This sample illustrates use of the HtmlInputFile control.
The following example shows a simple file upload scenario. When the user clicks the Upload button on the form, the file name, content type, and the amount of content in bytes are displayed on the page, while the file itself is uploaded to a specified directory on the server.
NOTE: When using this control, the Enctype property of the containing HtmlForm must be set to "multipart/form-data".
- The code for the form implements an HtmlForm control, an HtmlInputFile control, an HtmlInputText control, an HtmlInputButton control, and an HtmlGenericControl ( the Div element ).
<form enctype = "multipart/form-data" runat="server">
<p>File to Upload:
<input id="fileToUpload" type=file runat="server"></p>
<p>Save as filename ( no path ) :
<input id="fileName" type=text runat="server"></p>
<p><input type=button runat="server" id="Button1"
value="Upload" onServerClick = "uploadFile"></p>
<p><div id="details" runat="server" visible=false
style = "background:#def; border:1px inset" />
</p>
</form>
- In the <
head
> of the Web Forms page, define the handler for the file upload button’s Click event.
<script language="C#" runat="server">
void uploadFile ( object Source, EventArgs e ) {
if ( fileName.Value == "" ) {
details.InnerHtml = "You must enter a file name";
return;
}
if ( fileToUpload.PostedFile != null ) {
try {
fileToUpload.PostedFile.SaveAs ( "c:\\temp\\"+fileName.Value );
string html = "<p>File uploaded successfully on the web server</p>";
html += "<p>FileName: c:\\temp\\" + fileName.Value + "<br>";
html += "ContentType: " + fileToUpload.PostedFile.ContentType + "<br>";
html += "ContentLength: "+ fileToUpload.PostedFile.ContentLength + "</p>";
details.InnerHtml = html;
}
catch ( Exception exc ) {
details.InnerHtml = "Error saving file <b>c:\\temp\\" +
fileName.Value+"</b><br>" + exc.ToString ( );
}
finally {
details.Visible = true;
}
}
}
</script>
Web Forms Events and Handlers HtmlInputFile Class