How can I upload files asynchronously?
I would like to upload a file asynchronously with jQuery. This is my HTML:
<span>File</span>
<input type="file" id="file" name="file" size="10"/>
<input id="uploadbutton" type="button" value="Upload"/>
And here my JavaScript code:
$(document).ready(function () {
$("#uploadbutton").click(function () {
var filename = $("#file").val();
$.ajax({
type: "POST",
url: "addFile.do",
enctype: 'multipart/form-data',
data: {
file: filename
},
success: function () {
alert("Data Uploaded: ");
}
});
});
});
Instead of the file being uploaded, I am only getting the filename. What can I do to fix this problem?
Current Solution
I am using the jQuery Form Plugin to upload files.
Ajax
Javascript
jQuery
- asked 9 years ago
- B Butts
2Answer
With HTML5 you CAN make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME-type) or handle the progress event with the HTML5 progress tag (or a div). Recently I had to make a file uploader, but I didn't want to use Flash nor Iframes or plugins and after some research I came up with the solution.
The HTML:
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<progress></progress>
First, you can do some validation if you want. For example, in the onChange event of the file:
$(':file').change(function(){
var file = this.files[0];
var name = file.name;
var size = file.size;
var type = file.type;
//Your validation
});
Now the Ajax submit with the button's click:
$(':button').click(function(){
var formData = new FormData($('form')[0]);
$.ajax({
url: 'upload.php', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
beforeSend: beforeSendHandler,
success: completeHandler,
error: errorHandler,
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
Now if you want to handle the progress.
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
As you can see, with HTML5 (and some research) file uploading not only becomes possible but super easy. Try it with Google Chrome as some of the HTML5 components of the examples aren't available in every browser.
- answered 8 years ago
- G John
There are various ready-made plugins on doing file upload for jQuery.
Doing this kind of uploading hacks is not an enjoyable experience, so people enjoy using ready-made solutions.
Here's few:
You can search for more projects on NPM (using "jquery-plugin" as the keyword) or on Github.
- answered 8 years ago
- G John
Your Answer