jQuery File UPload plugin provides Multiple file uploads with progress bar. jQuery File Upload Plugin depends on Ajax Form Plugin, So Github contains source code with and without Form plugin.
1). Add the CSS and JS files in thehead
sections
<link href="http://hayageek.github.io/jQuery-Upload-File/uploadfile.min.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://hayageek.github.io/jQuery-Upload-File/jquery.uploadfile.min.js"></script>
body
to handle file uploads
<div id="fileuploader">Upload</div>
document
is ready.
<script>
$(document).ready(function()
{
$("#fileuploader").uploadFile({
url:"YOUR_FILE_UPLOAD_URL",
fileName:"myfile"
});
});
</script>
jQuery File upload plugin has the following features.
$("#singleupload").uploadFile({
url:"upload.php",
multiple:false,
dragDrop:false,
maxFileCount:1,
fileName:"myfile"
});
$("#multipleupload").uploadFile({
url:"upload.php",
multiple:true,
dragDrop:true,
fileName:"myfile"
});
$("#sequentialupload").uploadFile({
url:"upload.php",
fileName:"myfile",
sequential:true,
sequentialCount:1
});
$("#restrictupload1").uploadFile({
url:"upload.php",
fileName:"myfile",
acceptFiles:"image/*"
});
$("#restrictupload2").uploadFile({
url:"upload.php",
fileName:"myfile",
maxFileCount:3,
maxFileSize:100*1024
});
$("#localupload").uploadFile({
url:"upload.php",
fileName:"myfile",
dragDropStr: "<span><b>Faites glisser et déposez les fichiers</b></span>",
abortStr:"abandonner",
cancelStr:"résilier",
doneStr:"fait",
multiDragErrorStr: "Plusieurs Drag & Drop de fichiers ne sont pas autorisés.",
extErrorStr:"n'est pas autorisé. Extensions autorisées:",
sizeErrorStr:"n'est pas autorisé. Admis taille max:",
uploadErrorStr:"Upload n'est pas autorisé",
uploadStr:"Téléchargez"
});
$("#formdata1").uploadFile({
url:"upload.php",
fileName:"myfile",
formData: {"name":"Ravi","age":31}
});
$("#formdata2").uploadFile({
url:"upload.php",
fileName:"myfile",
dynamicFormData: function()
{
var data ={ location:"INDIA"}
return data;
}
});
var extraObj = $("#extraupload").uploadFile({
url:"upload.php",
fileName:"myfile",
extraHTML:function()
{
var html = "<div><b>File Tags:</b><input type='text' name='tags' value='' /> <br/>";
html += "<b>Category</b>:<select name='category'><option value='1'>ONE</option><option value='2'>TWO</option></select>";
html += "</div>";
return html;
},
autoSubmit:false
});
$("#extrabutton").click(function()
{
extraObj.startUpload();
});
var count=0;
$("#customupload1").uploadFile({
url:"upload.php",
fileName:"myfile",
showFileCounter:false,
customProgressBar: function(obj,s)
{
this.statusbar = $("<div class='custom-statusbar'></div>");
this.preview = $("<img class='custom-preview' />").width(s.previewWidth).height(s.previewHeight).appendTo(this.statusbar).hide();
this.filename = $("<div class='custom-filename'></div>").appendTo(this.statusbar);
this.progressDiv = $("<div class='custom-progress'>").appendTo(this.statusbar).hide();
this.progressbar = $("<div class='custom-bar'></div>").appendTo(this.progressDiv);
this.abort = $("<div>" + s.abortStr + "</div>").appendTo(this.statusbar).hide();
this.cancel = $("<div>" + s.cancelStr + "</div>").appendTo(this.statusbar).hide();
this.done = $("<div>" + s.doneStr + "</div>").appendTo(this.statusbar).hide();
this.download = $("<div>" + s.downloadStr + "</div>").appendTo(this.statusbar).hide();
this.del = $("<div>" + s.deletelStr + "</div>").appendTo(this.statusbar).hide();
this.abort.addClass("custom-red");
this.done.addClass("custom-green");
this.download.addClass("custom-green");
this.cancel.addClass("custom-red");
this.del.addClass("custom-red");
if(count++ %2 ==0)
this.statusbar.addClass("even");
else
this.statusbar.addClass("odd");
return this;
}
});
$("#eventsupload").uploadFile({
url:"upload.php",
multiple:true,
fileName:"myfile",
returnType:"json",
onLoad:function(obj)
{
$("#eventsmessage").html($("#eventsmessage").html()+"<br/>Widget Loaded:");
},
onSubmit:function(files)
{
$("#eventsmessage").html($("#eventsmessage").html()+"<br/>Submitting:"+JSON.stringify(files));
//return false;
},
onSuccess:function(files,data,xhr,pd)
{
$("#eventsmessage").html($("#eventsmessage").html()+"<br/>Success for: "+JSON.stringify(data));
},
afterUploadAll:function(obj)
{
$("#eventsmessage").html($("#eventsmessage").html()+"<br/>All files are uploaded");
},
onError: function(files,status,errMsg,pd)
{
$("#eventsmessage").html($("#eventsmessage").html()+"<br/>Error for: "+JSON.stringify(files));
},
onCancel:function(files,pd)
{
$("#eventsmessage").html($("#eventsmessage").html()+"<br/>Canceled files: "+JSON.stringify(files));
}
});
$("#deleteupload").uploadFile({url: "upload.php",
dragDrop: true,
fileName: "myfile",
returnType: "json",
showDelete: true,
showDownload:true,
statusBarWidth:600,
dragdropWidth:600,
deleteCallback: function (data, pd) {
for (var i = 0; i < data.length; i++) {
$.post("delete.php", {op: "delete",name: data[i]},
function (resp,textStatus, jqXHR) {
//Show Message
alert("File Deleted");
});
}
pd.statusbar.hide(); //You choice.
},
downloadCallback:function(filename,pd)
{
location.href="download.php?filename="+filename;
}
});
$("#previewupload").uploadFile({
url:"upload.php",
fileName:"myfile",
acceptFiles:"image/*",
showPreview:true,
previewHeight: "100px",
previewWidth: "100px",
});
$("#showoldupload").uploadFile({url: "upload.php",
dragDrop: true,
fileName: "myfile",
returnType: "json",
showDelete: true,
showDownload:true,
statusBarWidth:600,
dragdropWidth:600,
maxFileSize:200*1024,
showPreview:true,
previewHeight: "100px",
previewWidth: "100px",
onLoad:function(obj)
{
$.ajax({
cache: false,
url: "load.php",
dataType: "json",
success: function(data)
{
for(var i=0;i<data.length;i++)
{
obj.createProgress(data[i]["name"],data[i]["path"],data[i]["size"]);
}
}
});
},
deleteCallback: function (data, pd) {
for (var i = 0; i < data.length; i++) {
$.post("delete.php", {op: "delete",name: data[i]},
function (resp,textStatus, jqXHR) {
//Show Message
alert("File Deleted");
});
}
pd.statusbar.hide(); //You choice.
},
downloadCallback:function(filename,pd)
{
location.href="download.php?filename="+filename;
}
});
$("#singleupload1").uploadFile({
url:"http://hayageek.com/examples/jquery/ajax-multiple-file-upload/upload.php"
});
Output:
$("#singleupload2").uploadFile({
url:"http://hayageek.com/examples/jquery/ajax-multiple-file-upload/upload.php",
allowedTypes:"png,gif,jpg,jpeg",
fileName:"myfile"
});
Output:
var uploadObj = $("#advancedUpload").uploadFile({
url:"http://hayageek.com/examples/jquery/ajax-multiple-file-upload/upload.php",
multiple:true,
autoSubmit:false,
fileName:"myfile",
formData: {"name":"Ravi","age":31},
maxFileSize:1024*100,
maxFileCount:1,
dynamicFormData: function()
{
var data ={ location:"INDIA"}
return data;
},
showStatusAfterSuccess:false,
dragDropStr: "<span><b>Faites glisser et déposez les fichiers</b></span>",
abortStr:"abandonner",
cancelStr:"résilier",
doneStr:"fait",
multiDragErrorStr: "Plusieurs Drag & Drop de fichiers ne sont pas autorisés.",
extErrorStr:"n'est pas autorisé. Extensions autorisées:",
sizeErrorStr:"n'est pas autorisé. Admis taille max:",
uploadErrorStr:"Upload n'est pas autorisé"
});
$("#startUpload").click(function()
{
uploadObj.startUpload();
});
$("#deleteFileUpload").uploadFile({
url: "upload.php",
dragDrop: true,
fileName: "myfile",
returnType: "json",
showDelete: true,
deleteCallback: function (data, pd) {
for (var i = 0; i < data.length; i++) {
$.post("delete.php", {op: "delete",name: data[i]},
function (resp,textStatus, jqXHR) {
//Show Message
alert("File Deleted");
});
}
pd.statusbar.hide(); //You choice.
}
});
Output:
$("#multipleupload").uploadFile({
url:"http://hayageek.com/examples/jquery/ajax-multiple-file-upload/upload.php",
multiple:true,
fileName:"myfile"
});
$("#eventsupload").uploadFile({
url:"http://hayageek.com/examples/jquery/ajax-multiple-file-upload/upload.php",
multiple:true,
fileName:"myfile",
onSubmit:function(files)
{
$("#eventsmessage").html($("#eventsmessage").html()+"<br/>Submitting:"+JSON.stringify(files));
},
onSuccess:function(files,data,xhr)
{
$("#eventsmessage").html($("#eventsmessage").html()+"<br/>Success for: "+JSON.stringify(data));
},
afterUploadAll:function()
{
$("#eventsmessage").html($("#eventsmessage").html()+"<br/>All files are uploaded");
},
onError: function(files,status,errMsg)
{
$("#eventsmessage").html($("#eventsmessage").html()+"<br/>Error for: "+JSON.stringify(files));
}
});
$("#stylingupload1").uploadFile({
url:"http://hayageek.com/examples/jquery/ajax-multiple-file-upload/upload.php",
multiple:true,
fileName:"myfile",
showStatusAfterSuccess:false,
showAbort:false,
showDone:false,
});
$("#stylingupload2").uploadFile({
url:"http://hayageek.com/examples/jquery/ajax-multiple-file-upload/upload.php",
multiple:true,
fileName:"myfile",
showStatusAfterSuccess:false,
showAbort:false,
showDone:false,
uploadButtonClass:"ajax-file-upload-green"
});
Creates Ajax form and uploads the files to server.
var uploadObj = $("#uploadDivId").uploadFile(options);
uploads all the selected files. This function is used when autoSubmit
option is set to false
.
uploadObj.startUpload();
Aborts all the uploads
uploadObj.stopUpload();
Cancel all the selected files ( when autoSubmit:false)
uploadObj.cancelAll();
remove the widget from the document.
uploadObj.remove();
resets the widget properities
uploadObj.reset();
uploadObj.reset(false);//if you dont want remove the existing progress bars
Responses from the server are collected and returned.
uploadObj.getResponses()
Server URL which handles File uploads
Upload Form method type POST
or GET
. Default is POST
Upload Form enctype. Default is multipart/form-data
.
An object that should be send with file upload.
formData: { key1: 'value1', key2: 'value2' }
To provide form data dynamically
dynamicFormData: function()
{
//var data ="XYZ=1&ABCD=2";
var data ={"XYZ":1,"ABCD":2};
return data;
}
You can extra div elements to each statusbar. This is useful only when you set autoSubmit
to false
.
extraHTML:function()
{
var html = "<div><b>File tags:</b><input type='text' name='tags' value='' /> <br/>";
html += "<b>Directory</b>:<select name='values'><option value='1'>ONE</option><option value='2'>TWO</option></select>";
html += "</div>";
return html;
}
Using this you can add your own custom progress bar.
customProgressBar: function(obj,s)
{
this.statusbar = $("<div class='ajax-file-upload-statusbar'></div>");
this.preview = $("<img class='ajax-file-upload-preview' />").width(s.previewWidth).height(s.previewHeight).appendTo(this.statusbar).hide();
this.filename = $("<div class='ajax-file-upload-filename'></div>").appendTo(this.statusbar);
this.progressDiv = $("<div class='ajax-file-upload-progress'>").appendTo(this.statusbar).hide();
this.progressbar = $("<div class='ajax-file-upload-bar'></div>").appendTo(this.progressDiv);
this.abort = $("<div>" + s.abortStr + "</div>").appendTo(this.statusbar).hide();
this.cancel = $("<div>" + s.cancelStr + "</div>").appendTo(this.statusbar).hide();
this.done = $("<div>" + s.doneStr + "</div>").appendTo(this.statusbar).hide();
this.download = $("<div>" + s.downloadStr + "</div>").appendTo(this.statusbar).hide();
this.del = $("<div>" + s.deletelStr + "</div>").appendTo(this.statusbar).hide();
this.abort.addClass("ajax-file-upload-red");
this.done.addClass("ajax-file-upload-green");
this.download.addClass("ajax-file-upload-green");
this.cancel.addClass("ajax-file-upload-red");
this.del.addClass("ajax-file-upload-red");
if(count++ %2 ==0)
this.statusbar.addClass("even");
else
this.statusbar.addClass("odd");
return this;
}
Enables sequential upload. You can limit the number of uploads by sequentialCount
sequential:true,
sequentialCount:1
With the above configuration, only one file is uploaded at a time.
Allowed Maximum file Size in bytes.
Allowed Maximum number of files to be uploaded
Expected data type of the response. One of: null, 'xml', 'script', or 'json'. The dataType option provides a means for specifying how the server response should be handled. This maps directly to jQuery's dataType method. The following values are supported:
List of comma separated file extensions: Default is "*"
. Example: "jpg,png,gif"
accept MIME type for file browse dialog. Default is ""
. Example: "image/
"
check this for full list : http://stackoverflow.com/questions/11832930/html-input-file-accept-attribute-file-type-csv
Name of the file input field. Default is file
If it is set to true
, multiple file selection is allowed. Default isfalse
Drag drop is enabled if it is set to
If it is set to true
, files are uploaded automatically. Otherwise you need to call .startUpload
function. Default istrue
If it is set to false
, Cancel button is hidden when autoSubmit
is false. Default istrue
If it is set to false
, Abort button is hidden when the upload is in progress. Default istrue
If it is set to false
, Done button is hidden when the upload is completed. Default istrue
If it is set to true
, Delete button is shown when the upload is completed. Default isfalse
,You need to
implement deleteCallback() function.
If it is set to true
, Download button is shown when the upload is completed. Default isfalse
,You need to
implement downloadCallback() function.
If it is set to false
, status box will be hidden after the upload is done. Default istrue
If it is set to false
, Errors are not shown to user. Default istrue
If it is set to true
, File counter is shown with name. Default istrue
File Counter style can be changed using fileCounterStyle
. Default is ).
If it is set to true
, Progress precent is shown to user. Default isfalse
If it is set to true
, File size is shown
If it is set to true
, preview is shown to images. Default isfalse
is used to set preview height. Default is : "auto"
is used to set preview width. Default :"100%"
Using this you can place the progressbar wherever you want.
showQueueDiv: "output"
progress bar is added to a div with id output
Using this you can set status bar width
Using this you can set drag and drop div width
update plugin options runtime.
uploadObj.update({autoSubmit:true,maxFileCount:3,showDownload:false});
callback back to be invoked when the plugin is initialized. This can be used to show existing files..
onLoad:function(obj)
{
$.ajax({
cache: false,
url: "load.php",
dataType: "json",
success: function(data)
{
for(var i=0;i<data.length;i++)
{
obj.createProgress(data[i]);
}
}
});
},
callback back to be invoked when the file selected.
onSelect:function(files)
{
files[0].name;
files[0].size;
return true; //to allow file submission.
}
callback back to be invoked before the file upload.
onSubmit:function(files)
{
//files : List of files to be uploaded
//return flase; to stop upload
}
callback to be invoked when the upload is successful.
onSuccess:function(files,data,xhr,pd)
{
//files: list of files
//data: response from server
//xhr : jquer xhr object
}
callback to be invoked when all the files are uploaded.
afterUploadAll:function(obj)
{
//You can get data of the plugin using obj
}
callback to be invoked when the upload is failed.
onError: function(files,status,errMsg,pd)
{
//files: list of files
//status: error status
//errMsg: error message
}
callback to be invoked when user cancel the file ( when autosubmit:false)
onCancel: function(files,pd)
{
//files: list of files
//pd: progress div
}
callback to be invoked when the user clicks on Delete button.
deleteCallback: function(data,pd)
{
for(var i=0;i<data.length;i++)
{
$.post("delete.php",{op:"delete",name:data[i]},
function(resp, textStatus, jqXHR)
{
//Show Message
alert("File Deleted");
});
}
pd.statusbar.hide(); //You choice to hide/not.
}
callback to be invoked when the user clicks on Download button.
downloadCallback:function(files,pd)
{
location.href="download.php?filename="+files[0];
}
you can send custom errors from server. like "File exists". for custom errors,expected json object from server is:
{"jquery-upload-file-error":"File already exists"}
<?php
$output_dir = "uploads/";
if(isset($_FILES["myfile"]))
{
$ret = array();
$error =$_FILES["myfile"]["error"];
//You need to handle both cases
//If Any browser does not support serializing of multiple files using FormData()
if(!is_array($_FILES["myfile"]["name"])) //single file
{
$fileName = $_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$fileName);
$ret[]= $fileName;
}
else //Multiple files, file[]
{
$fileCount = count($_FILES["myfile"]["name"]);
for($i=0; $i < $fileCount; $i++)
{
$fileName = $_FILES["myfile"]["name"][$i];
move_uploaded_file($_FILES["myfile"]["tmp_name"][$i],$output_dir.$fileName);
$ret[]= $fileName;
}
}
echo json_encode($ret);
}
?>
<?php
$output_dir = "uploads/";
if(isset($_POST["op"]) && $_POST["op"] == "delete" && isset($_POST['name']))
{
$fileName =$_POST['name'];
$filePath = $output_dir. $fileName;
if (file_exists($filePath))
{
unlink($filePath);
}
echo "Deleted File ".$fileName."<br>";
}
?>
max_file_uploads = 2000
upload_max_filesize = 40000M
max_input_vars = 10000
post_max_size = 40000M
php_value suhosin.post.max_vars 10000
php_value suhosin.request.max_vars 10000
php_value suhosin.get.max_array_depth 2000
php_value suhosin.get.max_vars 10000
php_value suhosin.upload.max_uploads 2000