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.
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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With