Untill now, I've been using 2 controls (FileUpload and additional button). After file was chosen in a fileUpload control, user had to accept his choice by pressing save button.
Here's button's code:
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
FileUpload1.SaveAs(Server.MapPath("~/file.jpg"));
Label1.Text = Server.MapPath("~/file.jpg");
Image1.ImageUrl = "file.jpg";
}
}
I'm wondering whether there is a way to avoid using that button, so the FileUpload control's button would do the additional button's job.
The FileUpload
control renders an <input type="file>
in the browser. You can use the javascript change
event to trigger the upload.
First make sure you have a load
event handler registered in the body
of your page:
<body onload="body_onload()">
And add this code inside your event handler:
<script type="text/javascript">
function body_onload()
{
...
$get('<%=FileUpload.ClientID%>').onchange = function() {
$get('<%=this.Page.Form.ClientID%>').submit();
};
}
</script>
Or to do this using pure jQuery, place this in the head
of your page (if you don't already have jQuery included):
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
Then use this code to bind to the event (replace #fileUpload1
and #form1
with the id's of your FileUpload
and Form
elements, respectively):
<script type="text/javascript">
$(document).ready(function() {
$("#fileUpload1").change(function() {
$("#form1").submit();
});
});
</script>
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