jQuery Upload File 多文件批量上传插件

发布于 2018-06-13 23:05:05 字数 26357 浏览 4320 评论 0

jQuery File UPload 包含多个带有进度条的文件上传,能够兼容任意的服务端语言,例如 PHP、Python、Ruby on Rails、Java等,支持标准的HTML表单文件上传。jQuery 文件上传插件依赖于Ajax表单插件,所以 github 地址上包含有和没有表单插件的源代码。

快速入门

1、引入 CSS 和 JavaScript 文件

<link href="css/uploadfile.css" rel="stylesheet">
<script src="js/jquery.min.js"></script>
<script src="js/jquery.uploadfile.min.js"></script>

2、为文件添加一个 DIV 来处理文件上传

<div>Upload</div>

3、在网页加载完毕以后初始化插件

$(document).ready(function(){
	$("#fileuploader").uploadFile({
	url:"YOUR_FILE_UPLOAD_URL",
	fileName:"myfile"
	});
});

就是这样 JQuery AJAX File Uploader 已经准备好了。

插件特点

jQuery File upload 插件具有以下特点。

1).单文件上传

使用下面的配置,插件只允许单个文件上传(不拖拽)。

$("#singleupload").uploadFile({
	url:"upload.php",
	multiple:false,
	dragDrop:false,
	maxFileCount:1,
	fileName:"myfile"
});

2).多文件上传(拖放)

通过下面的配置,插件支持多文件上传与拖放。

$("#multipleupload").uploadFile({
	url:"upload.php",
	multiple:true,
	dragDrop:true,
	fileName:"myfile"
});

3).Sequential file Upload

With the below configuration, plugin uploads the file sequentially. you can control number of active uploads with sequentialCount.
Source:

$("#sequentialupload").uploadFile({
url:"upload.php",
fileName:"myfile",
sequential:true,
sequentialCount:1
}); 

4).Upload with File Restrictions

With the below configuration, plugin allows only specific file types.
Source:

$("#restrictupload1").uploadFile({
url:"upload.php",
fileName:"myfile",
acceptFiles:"image/*"
}); 

With the below configuration, plugin allows only files lesser than the specified size/count.

$("#restrictupload2").uploadFile({
url:"upload.php",
fileName:"myfile",
maxFileCount:3,
maxFileSize:100*1024
}); 

5).Localization

With the below configuration, you can change all the plugin strings.

$("#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"
});

6).Sending Form Data

With the below configuration, plugin sends the form data with every file uploaded. form data can be accessed at server side using $_POST.
Source:

$("#formdata1").uploadFile({
url:"upload.php",
fileName:"myfile",
formData: {"name":"Ravi","age":31}
}); 

With the below configuration, plugin sends dynamic form data with every file upload. For example, if you want to send updated 'input' value with the uploaded file.
Source:

$("#formdata2").uploadFile({
url:"upload.php",
fileName:"myfile",
dynamicFormData: function(){
	var data ={ location:"INDIA"}
	return data;
}
}); 

7).Add extra HTML Elements

With the below configuration,plugin allows to add extra HTML elements (input,textarea,select) to status bar.
Source:

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();
});

8).Custom UI

Using the below configuration, you can design your own progress bar.
Source:

var count=0;
$("#customupload1").uploadFile({
	url:"upload.php",
	fileName:"myfile",
	showFileCounter:false,
	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.deleteStr + "</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;
	    }
});

9).Upload Events

Below are the different callback events. Source:

$("#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));
}
});

10).Delete/Download Files

With the below configuration, plugin supports File download and File delete features. Source:

$("#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;
}
});

11).Image Preview

To enable image preview, use the below configuration. Source:

$("#previewupload").uploadFile({
url:"upload.php",
fileName:"myfile",
acceptFiles:"image/*",
showPreview:true,
previewHeight: "100px",
previewWidth: "100px",
});

12).Show already uploaded files

With the below configuration,plugin loads the previousily uploaded files. Source:

$("#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;
	}
}); 

Jquery File Upload

$("#singleupload1").uploadFile({
	url:"http://hayageek.com/examples/jquery/ajax-multiple-file-upload/upload.php"
});

Jquery File Upload with File Restrictions

$("#singleupload2").uploadFile({
url:"http://hayageek.com/examples/jquery/ajax-multiple-file-upload/upload.php",
allowedTypes:"png,gif,jpg,jpeg",
fileName:"myfile"
});

Jquery Advanced File Upload

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();
});

Jquery Delete File Option

$("#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.
}
});

Jquery Multiple File Upload

$("#multipleupload").uploadFile({
url:"http://hayageek.com/examples/jquery/ajax-multiple-file-upload/upload.php",
multiple:true,
fileName:"myfile"
});

Jquery Upload File Events

$("#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));
}
});

Hide Cancel,Abort,Done Buttons

$("#stylingupload1").uploadFile({
url:"http://hayageek.com/examples/jquery/ajax-multiple-file-upload/upload.php",
multiple:true,
fileName:"myfile",
showStatusAfterSuccess:false,
showAbort:false,
showDone:false,
});

Changing Upload Button style

$("#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"
});

方法事件

uploadFile( options )

Creates Ajax form and uploads the files to server.

var uploadObj = $("#uploadDivId").uploadFile(options);

startUpload()

uploads all the selected files. This function is used when autoSubmit option is set to false.

uploadObj.startUpload();

stopUpload()

Aborts all the uploads

uploadObj.stopUpload();

cancelAll()

Cancel all the selected files ( when autoSubmit:false)

uploadObj.cancelAll();

remove()

remove the widget from the document.

uploadObj.remove();

reset()

resets the widget properities

uploadObj.reset();
uploadObj.reset(false);//if you dont want remove the existing progress bars

getResponses()

Responses from the server are collected and returned.

uploadObj.getResponses()

可选参数

url

Server URL which handles File uploads

method

Upload Form method type POST or GET. Default is POST

enctype

Upload Form enctype. Default is multipart/form-data.

formData

An object that should be send with file upload.

formData: { key1: 'value1', key2: 'value2' }

dynamicFormData

To provide form data dynamically

dynamicFormData: function(){
    //var data ="XYZ=1&ABCD=2";
    var data ={"XYZ":1,"ABCD":2};
    return data;        
}

extraHTML

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;
}

customProgressBar

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.deleteStr + "</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;
}

sequential

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.

maxFileSize

Allowed Maximum file Size in bytes.

maxFileCount

Allowed Maximum number of files to be uploaded

returnType

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:

  • 'xml': server response is treated as XML and the 'success' callback method, if specified, will be passed the responseXML value
  • 'json': server response will be evaluted and passed to the 'success' callback, if specified
  • 'script': server response is evaluated in the global context

allowedTypes

List of comma separated file extensions: Default is "*". Example: "jpg,png,gif"

acceptFiles

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

fileName

Name of the file input field. Default is file

multiple

If it is set to true, multiple file selection is allowed. Default isfalse

dragDrop

Drag drop is enabled if it is set to true

autoSubmit

If it is set to true, files are uploaded automatically. Otherwise you need to call .startUpload function. Default istrue

showCancel

If it is set to false, Cancel button is hidden when autoSubmit is false. Default istrue

showAbort

If it is set to false, Abort button is hidden when the upload is in progress. Default istrue

showDone

If it is set to false, Done button is hidden when the upload is completed. Default istrue

showDelete

If it is set to true, Delete button is shown when the upload is completed. Default isfalse,You need to implement deleteCallback() function.

showDownload

If it is set to true, Download button is shown when the upload is completed. Default isfalse,You need to implement downloadCallback() function.

showStatusAfterSuccess

If it is set to false, status box will be hidden after the upload is done. Default istrue

showError

If it is set to false, Errors are not shown to user. Default istrue

showFileCounter

If it is set to true, File counter is shown with name. Default istrue File Counter style can be changed using fileCounterStyle. Default is ).

showProgress

If it is set to true, Progress precent is shown to user. Default isfalse

showFileSize

If it is set to true, File size is shown

showPreview

If it is set to true, preview is shown to images. Default isfalse

previewHeight

is used to set preview height. Default is : "auto"

previewWidth

is used to set preview width. Default :"100%"

showQueueDiv

Using this you can place the progressbar wherever you want.

showQueueDiv: "output"

progress bar is added to a div with id output

statusBarWidth

Using this you can set status bar width

dragdropWidth

Using this you can set drag and drop div width

update

update plugin options runtime.

uploadObj.update({autoSubmit:true,maxFileCount:3,showDownload:false});

Callbacks

onLoad

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]);
			}
		}
    });
},

onSelect

callback back to be invoked when the file selected.

onSelect:function(files){
    files[0].name;
    files[0].size;
    return true; //to allow file submission.
}

onSubmit

callback back to be invoked before the file upload.

onSubmit:function(files){
    //files : List of files to be uploaded
    //return flase;   to stop upload
}

onSuccess

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
}

afterUploadAll

callback to be invoked when all the files are uploaded.

afterUploadAll:function(obj){
    //You can get data of the plugin using obj
}

onError

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
}

onCancel

callback to be invoked when user cancel the file ( when autosubmit:false)

onCancel: function(files,pd){
    //files: list of files
    //pd:  progress div
}

deleteCallback

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.

}

downloadCallback

callback to be invoked when the user clicks on Download button.

downloadCallback:function(files,pd){
    location.href="download.php?filename="+files[0];
}

Localisation

dragDropStr

Drag & Drop text. Default value: "Drag & Drop Files"

uploadStr

Upload button text. Default value: "Upload"

abortStr

Abort button text Default Value: "Abort"

cancelStr

Cancel button text. Default value: "Cancel"

doneStr

Done button text. Default value: "Done"

multiDragErrorStr

Default value: "Multiple File Drag & Drop is not allowed."

extErrorStr

Default value: "is not allowed. Allowed extensions: "

duplicateErrorStr

Default value: "is not allowed. File already exists."

sizeErrorStr

Default value: "is not allowed. Allowed Max size: "

uploadErrorStr

Default value: "Upload is not allowed"

maxFileCountErrorStr

Default value: " is not allowed. Maximum allowed files are:"

Custom Errors

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"}

Note: You have to set returnType: "json"

PHP Files

upload.php
download.php
delete.php
load.php

Server settings for Large file uploads

php.ini settings

max_file_uploads = 2000
upload_max_filesize = 40000M
max_input_vars = 10000
post_max_size = 40000M

httpd.conf settings

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

JSmiles

生命进入颠沛而奔忙的本质状态,并将以不断告别和相遇的陈旧方式继续下去。

0 文章
0 评论
84960 人气
更多

推荐作者

遂心如意

文章 0 评论 0

5513090242

文章 0 评论 0

巷雨优美回忆

文章 0 评论 0

junpengz2000

文章 0 评论 0

13郎

文章 0 评论 0

qq_xU4RDg

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文