问题
I am trying to build the page to upload the file by using AJAX, JQUERY and .Net HTTPHandler as in http://dotnet.dzone.com/news/async-file-upload-jquery-and
It works only for the first time I chose a file and uploaded it. But it doesn't work when I select the file next time and doesn't show any error.
If I change the javascript event binding to the old school way like the following, it works perfectly. But I want to use the JQuery Binding. Is there anything I did wrongly? Thanks.
<input id="fileToUpload" type="file" size="45" name="fileToUpload" class="input" onchange="return ajaxFileUpload();">
HTML Code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="StudentID" HeaderText="ID" />
<asp:BoundField DataField="name" HeaderText="Name" />
<asp:TemplateField>
<ItemTemplate>
<input id="fileToUpload" type="file" size="45" name="fileToUpload" class="fileToUpload" >
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
JQuery Binding Code:
<script>
$().ready(function () {
$(".fileToUpload").change(function() {
$.ajaxFileUpload
(
{
url: 'AJaxUploadHandler.ashx',
secureuri: false,
fileElementId: 'fileToUpload',
dataType: 'json',
data: { name: 'logan', id: 'id' },
success: function (data, status) {
if (typeof (data.error) != 'undefined') {
if (data.error != '') {
console.log(data.error);
} else {
console.log(data.msg);
}
}
},
error: function (data, status, e) {
alert(e);
}
}
)
return false;
});
});
</script>
回答1:
Use .on method as shown below and try again
$(".fileToUpload").on('change', function() {
///// Your code
});
回答2:
This has worked for me.
$(document).on("change", "#inputId", function(){
//Do something
});
For performance it is better to avoiding using $(document)
and call the on() method on a wrapper div like this.
<div id="wrapper">
<input id="#inputId" type="file"/>
</div>
$("#wrapper").on("change", "#inputId", function(){
//Do something
});
It has to do with Direct and delegated events: http://api.jquery.com/on/
回答3:
I had a similar issue. If I tried to upload the exact same file name at the exact same location. Then the change event would basically say no change. I ended up using a click even, checked for $(this).val() and call the the change event inside the click event handler.
$("input[type='file']").on('click', function () {
if(!$(this).val()){
//Initial Case when no document has been uploaded
$("input[type='file']").change(function(){
upload_file_setup(this);
});
}else{
//Subsequent cases when the exact same document will be uploaded several times
$(this).val('');
$("input[type='file']").unbind('change');
$("input[type='file']").change(function(){
upload_file_setup(this);
});
}
});
The unbind may not be necessary but it works for me.
来源:https://stackoverflow.com/questions/23424417/file-upload-control-onchange-event-jquery