Rather than using the standard file upload mechanism often it’s more convenient to use the XMLHttpRequest API and to upload files in non-blocking manner with asynchronous requests. This blog post describes how to accomplish this with the help of jQuery and the Upload plugin. In addition the cross-domain file upload is discussed too.
Let’s start with adding the required libraries to the web page:
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://static.zinoui.com/1.5/compiled/zino.upload.min.js"></script>
The HTML element used as container of this ajax uploader must be placed outside of any
FORM
elements.<!-- This is the container where the upload button will appear -->
<div id="upload"></div>
AJAX FILE UPLOAD
The file handler and http method are the only options you need to setting up before start.
$("#upload").zinoUpload({
method: "POST",
url: "upload.php"
});
AJAX MULTIPLE FILE UPLOAD
For multiple file upload the name of form parameter must ends with square brackets
[]
. Also the multiple
property must be set to true
.$("#upload").zinoUpload({
method: "POST",
url: "upload.php",
name: "files[]",
multiple: true
});
SEND ADDITIONAL DATA WITH FILE UPLOAD
To submit additional data alongside with the POST request, use the
data
property.$("#upload").zinoUpload({
method: "POST",
url: "upload.php",
data: {
"product": 42,
"color": "blue"
}
});
UPLOAD CALLBACKS
Handling the states of file upload process is provided by 3 callbacks:
change
, submit
and complete
.$("#upload").zinoUpload({
method: "POST",
url: "upload.php",
change: function (event, ui) {
//console.log(ui);
},
submit: function (event, ui) {
//console.log(ui);
},
complete: function (event, ui) {
//console.log(ui);
}
});
CROSS-DOMAIN AJAX FILE UPLOAD
Let’s see an example of
upload.php
, the PHP script who is responsible to process the file upload.<?php
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
//header("Access-Control-Allow-Origin: *");
}
header('Content-Type: application/json; charset=utf-8');
if (isset($_FILES['file']) && is_uploaded_file($_FILES['file']['tmp_name'])
&& $_FILES['file']['error'] == UPLOAD_ERR_OK) {
if (move_uploaded_file($_FILES['file']['tmp_name'], '/uploads/' . basename($_FILES['file']['name']))) {
// File is valid, and was successfully uploaded
echo json_encode(array('status' => 'OK'));
} else {
echo json_encode(array('status' => 'ERR'));
}
} else {
echo json_encode(array('status' => 'FAIL'));
}
exit;
?>
CONCLUSION
A demo of above code examples you can find out at cross-domain ajax upload demo page. To see more use cases explore our upload plugin’ demo pages. For complete list of configuration options please read the API documentation.