Question

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.

Was it helpful?

Solution

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

OTHER TIPS

Try this way:

<form id="frmUpload" enctype="multipart/form-data" runat="server" >
 <input type="file" id="FilesToUpload" name="FilesToUpload" />
 <asp:Button ID="UploadFiles" OnClick="ClickUpload" Text="Upload File . . ." runat="server"/>
</form>

and in code part:

protected void ClickUpload(object sender, EventArgs e)
{
    String fileToUpload = Request.Files["FilesToUpload"];

    //check file if exists for submitted
    if (fileToUpload != null && fileToUpload.ContentLength > 0)
    {
        string FileName = Path.GetFileName(fileToUpload.FileName);
        fileToUpload.SaveAs(Server.MapPath(Path.Combine("~/YourFileFolder/", FileName)));
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top