September 2, 2013 08:48 by
Scott
OK, I will talk again about FileUpload Control. Last week I have discussed about how to fix FileUpload Control that not work in Update Panel. FileUpload Control really help us to accepting file uploads from users. It is very easy now. Please see the example below. 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.
This example will get the job done, but as you can see, nothing is checked. The user can upload any kind of file, and the size of the file is only limited by the server configuration. A more robust example could look like this:
protected void UploadButton_Click(object sender, EventArgs e)
{
if(FileUploadControl.HasFile)
{
try
{
if(FileUploadControl.PostedFile.ContentType == "image/jpeg")
{
if(FileUploadControl.PostedFile.ContentLength < 102400)
{
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/") +
filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
else
StatusLabel.Text = "Upload status: The file has to be less than 100 kb!";
}
else
StatusLabel.Text = "Upload status: Only JPEG files are accepted!";
}
catch(Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
Here we use the two properties, ContentLength and ContentType, to do some basic checking of the file which the user is trying to upload. The status messages should clearly indicate what they are all about, and you can change them to fit your needs.