I am using jQuery File Upload to asynchronously upload images to a .NET MVC controller. I have the following script that runs
<script type="text/javascript">
$('#Image').fileupload({
url: "/Home/PostUpdate",
dataType: 'json',
replaceFileInput: false,
dropZone: null,
autoUpload: false,
maxNumberOfFiles: 1,
maxFileSize: 2000000,
add: function (e, data) {
$("form").submit(function (event) {
event.preventDefault();
console.log("posting from jquery file upload");
if ($("#Image")[0].files[0].size > 0 && ($("#PostText").val() === "" || $("#PostText").val() === undefined)) {
// Warning message here
}
else {
console.log("2a");
data.submit();
}
});
},
done: function (e, data) {
// Done code here...
}
});
$("form").submit(function (event) {
event.preventDefault();
if ($("#Image")[0].files[0] == undefined) {
console.log("posting from default ajax");
var url = "/Home/PostUpdate/";
$.ajax({
url: url,
datatype: "json",
data: $(this).serialize(),
cache: false,
type: "POST",
success: function (data) {
// Success code here
},
error: function (response) {
alert("error");
}
});
}
});
</script>
My HTML is a standard <input type="file"/>
, and so I can attach a file and upload and I see the file go through to the server-side code. I process, and add to the database, without issue.
The first image I select, uploads once. If I then choose a second image and upload, it performs the upload and hits the MVC controller twice. If I choose a third image, the upload happens three times? It always hits the same data.submit()
namely the one that occurs at console.log("2a")
but I am at a loss as to why it would occur multiple times?
I'm wondering if the event.preventDefault() is causing this to fire? But that wouldn't make sense as to why I get three, then four, then five posts to the controller action?
Has anyone else had this and if so, what did you implement to fix it?
Thanks in advance!
This seems to be an underlying plugin problem where the solution would be to unbind and rebind the click event:
Since I'm not convinced the plausible duplicate flag yields the best solution, I dug a little deeper:
It's also possible the change event fileuploadchange
works better than fileuploadadd
. You could try to use { change: function(){/**/} }
instead of { add: function(){/**/} }
but it seems a bit ambiguous.
Another post talks about the submit button actively submitting the form while that should not be the correct way to implement it.
By default, the file input field is replaced with a clone after each input field change event. This is required for iframe transport queues and allows change events to be fired for the same file selection, but can be disabled by setting this option to false (more in-depth information can be found in the FAQ).
Set it on true
and test again.
Why is the file input field cloned and replaced after each selection?
The cloning is done for two reasons: