ASP.NET Tip: ASP.NET 2.0 Introduces FileUpload Control
One of the things that always baffles me about ASP.NET is why some HTML controls (such as text boxes and images) have ASP.NET equivalents and others (such as the file upload control) don't. ASP.NET 2.0 rectifies this situation with the new FileUpload control, which is designed to replace the input type=file control. While the HtmlInputFile control works fine in ASP.NET 2.0, the FileUpload control makes the implementation a bit cleaner.
<table>
<tr>
<td>Select file:</td>
<td><input type="file" runat="server" id="ctlFile"></td>
</tr>
<tr>
<td colspan="2"><asp:LinkButton ID="btnSave" Runat="server">
Save</asp:LinkButton></td>
</tr>
</table>
Here's the typical back-end C# code to process the uploaded file:
void btnSave_Click(object sender, EventArgs e)
{
// Other validation code
if (ctlFile.PostedFile.FileName == "")
// display some sort of error
else
ctlFile.PostedFile.SaveAs("C:\\Inetpub\\wwwroot\\
somefilename.dat");
// Other code to handle save routine
}
The new FileUpload control replaces the old control very easily. The new HTML looks like this:
<table>
<tr>
<td>Select file:</td>
<td><asp:FileUpload runat="server" id="ctlFile"></td>
</tr>
<tr>
<td colspan="2"><asp:LinkButton ID="btnSave" Runat="server">
Save</asp:LinkButton></td>
</tr>
</table>
void btnSave_Click(object sender, EventArgs e)
{
// Other validation code
if (!ctlFile.HasFile)
// display some sort of error
else
ctlFile.PostedFile.SaveAs("C:\\Inetpub\\wwwroot\\
somefilename.dat");
// Other code to handle save routine
}
No comments:
Post a Comment