我在我的幾個網站上使用該片段,它處理多文件上傳,拖放和進度條。
HTML
您將需要一個容器來放棄你的文件的批處理,在我們的情況下,它會被#output和文件的列表。
JS
首先,我們將推動數據傳遞到jQuery的事件並綁定drop事件。
$(document).ready(function(){
// We add the dataTransfer special property to our jQuery event
$.event.props.push("dataTransfer");
// We bind events for drag and drop
$('#output').bind({
"dragenter dragexit dragover" : do_nothing,
drop : drop
});
});
// stop event propagation
function do_nothing(evt){
evt.stopPropagation();
evt.preventDefault();
}
然後我們建立我們的更新進度功能
// Progress bar update function
function update_progress(evt,fic) {
var id_tmp=fic.size;
//id_tmp help us keep track of which file is uploaded
//right now it uses the filesize as an ID: script will break if 2 files have the
// same size
if (evt.lengthComputable) {
var percentLoaded = Math.round((evt.loaded/evt.total) * 100);
if (percentLoaded <= 100) {
$('#'+id_tmp+' .percent').css('width', percentLoaded + '%');
$('#'+id_tmp+' .percent').html(percentLoaded + '%');
}
}
}
最後但並非最不重要我們降功能
function drop(evt){
do_nothing(evt);
var files = evt.dataTransfer.files;
// Checking if there are files
if(files.length>0){
for(var i in files){
// if its really a file
if(files[i].size!=undefined) {
var fic=files[i];
// We add a progress listener
xhr = jQuery.ajaxSettings.xhr();
if(xhr.upload){
xhr.upload.addEventListener('progress', function (e) {
update_progress(e,fic);
},false);
}
provider=function(){ return xhr; };
// We build our FormData object
var fd=new FormData;
fd.append('fic',fic);
// For each file we build and Ajax request
$.ajax({
url:'/path/to/save_fic.php',
type: 'POST',
data: fd,
xhr:provider,
processData:false,
contentType:false,
complete:function(data){
//on complete we set the progress to 100%
$('#'+data.responseText+' .percent').css('width', '100%');
$('#'+data.responseText+' .percent').html('100%');
}
});
// for each file we setup a progress bar
var id_tmp=fic.size;
$('#output').after('<div class="progress_bar loading" id="'+id_tmp+'"><div class="percent">0%</div></div>');
$('#output').addClass('output_on');
// We add our file to the list
$('#output-listing').append('<li>'+files[i].name+'</li>');
}
}
}
}
該方法不IE9以下工作。 希望它有幫助! Source(in french)
Some infos on progress tracking using XMLHttpRequest
Some infos on the datatransfer prop
編輯:
PHP
從服務器端,您可以處理正常使用$ _FILES等等 文件爲了在你的PHP腳本必須迴應的完整功能中將進度設置爲100% 文件大小。
這可能會有幫助:https://github.com/blueimp/jQuery-File-Upload – Lekhnath
將圖像轉換爲字符串並加密該字符串值並將其發送到Web服務。在Web服務端解密並移動圖像 – MAK