I want to upload files asynchronously using jQuery. This is my HTML:
<input type="file" id="f" name="f"/>
<input id="upload" type="button" value="Upload"/>
And here my JavaScript code:
$(document).ready(function () {
$("#upload").click(function () {
var filename = $("#f").val();
$.ajax({
type: "POST",
url: "addFile.do",
enctype: 'multipart/form-data',
data: {
file: filename
},
success: function () {
alert("All Files Have Been Uploaded ");
}
});
});
});
I am getting file names only instead of actual file which I have uploaded
I am using theThis Plugin to upload files.
Unlike you think, the code does NOT use that plugin to upload files. Instead you explicitly make an ajax request. The error occurs because the value of the <input type="file">
is the filename, and that is the only data you are sending in the request.
Instead you need to bind the form using $(form).ajaxform()
; then in the click handler, you can trigger the submit event on the form.
Thus something like as follows ought to do the trick:
html:
<form method="post" action="addFile.do">
<input type="file" id="f" name="f"/>
<input id="upload" type="button" value="Upload"/>
</form>
And JavaScript:
$('form').ajaxform({
success: function () {
alert("All Files Have Been Uploaded ");
}
});
$("#upload").click(function() {
$('form').submit();
});
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