Home > Getting Started > ASP.NET Syntax > ASP.NET Syntax for HTML Controls > HtmlInputFile
HtmlInputFile Class Input File Element
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.
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.
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>Save as filename ( no path ) :
<input id="fileName" type=text runat="server">
<p><input type=button runat="server" id="Button1"
value="Upload" onServerClick = "uploadFile">
<p><div id="details" runat="server" visible=false
style = "background:#def; border:1px inset" />
</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>
HtmlInputFile Class Input File Element