What is FileUpload in ASP.NET?
Uploading files and image from PCs into Server
uploading of the files using ASP.NET and C#.
With the FileUpload control, it can be done with a small amount of code lines, as you will see in the following example. However, please notice that there are security concerns to to consider when accepting files from users! Here is the markup required:
Uploading files and image from PCs into Server
uploading of the files using ASP.NET and C#.
With the FileUpload control, it can be done with a small amount of code lines, as you will see in the following example. However, please notice that there are security concerns to to consider when accepting files from users! Here is the markup required:
<form id="form1" runat="server">
<asp:FileUpload id="FileUploadControl" runat="server" />
<asp:Button runat="server" id="UploadButton" text="Upload"
onclick="UploadButton_Click" />
<br /><br />
<asp:Label runat="server" id="StatusLabel" text="Upload status: " />
</form>
And here is the CodeBehind code required to handle the upload:
protected void UploadButton_Click(object sender, EventArgs e)
{
if(FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
catch(Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The
following error occured: " + ex.Message;
}
}
}
As you can see, it's all relatively simple. Once the UploadButton is
clicked, we check to see if a file has been specified in the upload
control. If it has, we use the FileUpload controls SaveAs method to save
the file. We use the root of our project (we use the MapPath method to
get this) as well as the name part of the path which the user specified.
If everything goes okay, we notify the user by setting the Text
property of the StatusLabel - if not, an exception will be thrown, and
we notify the user as well.
No comments:
Post a Comment