Uploading with HTML5 (FormData )
If FormData and the File API are supported, you can upload files with jQuery using the $.ajax() method (both HTML5 features).
FormData may also be used to transmit files. Include a file-type input element in your form:
<form enctype="multipart/form-data" method="post" name="uploadinfo">
<label>Email:</label>
<input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" /><br />
<label>File Name:</label>
<input type="text" name="name" size="12" maxlength="32" /><br />
<label>Upload:</label>
<input type="file" name="upload" required />
<input type="submit" value="Upload!" />
</form>
<div></div>
Then use the following code below to send it:
var form = document.forms.namedItem("uploadinfo");
form.addEventListener('submit', function(ev) {
var oOutput = document.querySelector("div"),
oData = new FormData(form);
oData.append("CustomField", "This is some extra data");
var oReq = new XMLHttpRequest();
oReq.open("POST", "stash.php", true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
oOutput.innerHTML = "Uploaded!";
} else {
oOutput.innerHTML = "Error " + oReq.status + " occurred when trying to upload your file.<br \/>";
}
};
oReq.send(oData);
ev.preventDefault();
}, false);
JQUERY FILES UPLOADER
This is an AJAX-based file upload. The jQuery plugin just uploads the file and provides the response to a callback.
HTML:
<input type="file" id="one-specific-file" name="one-specific-file">
jQuery Minimum use:
//use the bare minimum
$('#one-specific-file').ajaxfileupload({
'action': '/upload.php'
});
Max use of jQuery:
$('input[type="file"]').ajaxfileupload({
'action': '/upload.php',
'params': {
'extra': 'info'
},
'onComplete': function(response) {
console.log('custom handler for file:');
alert(JSON.stringify(response));
},
'onStart': function() {
if(weWantedTo) return false; // cancels upload
},
'onCancel': function() {
console.log('no file selected');
}
});
- It does not need a specific response from your server.
- It doesn’t require any special HTML; simply give it an input type=”file”>.
- It makes no difference how many files you utilize or where they are placed on the page.