C# Webform file upload with button postback not with POST

HenrikP picture HenrikP · Mar 19, 2014 · Viewed 9.7k times · Source

I have a Webform(aspx) page.

In it we basically have this form that we "post" when pressing a button, but in reality it is not a true httpPOST, it is actually just a postback onclick event on that button. Within that event we get all information we want like what the user has typed in the textfields and so on. Which by the way works great.

But now I want to add a file uploader, more specifically an image uploader.

Can I grab the file the user has uploaded to the input type file from codebehind within a button event click postback? not a httppost.

Answer

nasskov picture nasskov · Mar 19, 2014

There is a specific control for this, FileUpload. Just add it on the page and you can get the uploaded file from this control on postback, quite similar to the other controls on page, like textboxes etc. for more info: http://asp.net-tutorials.com/controls/file-upload-control/

aspx page:

<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>

Code Behind:

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;
        }
    }
}