JSFiddle - React, Tailwind, and code Playground
by Noir Noir
HTML
<form action="<?php echo Yii::app()->createUrl('catalogue/uploadProcess'); ?>" method="post" enctype="multipart/form-data">
<div class="field field-files">
<input type="file" name="files[]" multiple />
</div>
<div class="progress-bar">
<p class="state"></p>
<div class="line"></div>
<p class="percent"></p>
</div>
<div class="buttons">
<input type="button" name="send" value="Загрузить"/>
</div>
</form>
CSS
.upload-files-form .progress-bar .line,
.upload-files-form .progress-bar .percent {
display: inline-block;
}
.upload-files-form .progress-bar .line {
height: 30px;
margin-right: 10px;
background: #0284c8;
}
JavaScript
function resetProgressBar() {
$('.percent', progressBar).html('0%');
$('.line', progressBar).width(0);
$('.state', progressBar).text('Загрузка...');
}
function setProgressBar(percent) {
$('.state', progressBar).text(percent == 100 ? '' : 'Загрузка...');
$('.percent', progressBar).html(percent+'%');
$('.line', progressBar).width(Math.ceil(progressBarWidth*(percent/100)));
}
function uploadFile(url, file) {
resetProgressBar();
var reader = new FileReader();
reader.onload = function(e){
uploadFileData(url, file, e.target.result);
};
reader.readAsDataURL(file);
}
function uploadFileData(url, file, fileData) {
var comma = fileData.indexOf(',');
if (comma>0) fileData = fileData.substring(comma+1); // Отрезаем заголовок Data::URL
// console.log(fileData);
var pos = 0,
err = false,
partsCount = Math.ceil(fileData.length / upload_chunk_size),
partsIndex = 0;
while (pos<fileData.length && !err) {
partsIndex++;
$.ajax({
url: url,
type : 'POST',
async: false, // надо чтобы части файла грузились последовательно
data: {
group: file.group,
filename: file.name,
data: fileData.substring(pos,pos+upload_chunk_size), // Кусок файла
start: +(pos <= 0)
},
error: function(){
addError('Ошибка загрузки файла "'+file.name+'"');
err = true;
},
success: function(){
// addMessage('Файл "'+file.name+'" загружен');
setProgressBar(Math.ceil(100*partsIndex/partsCount));
if (partsIndex >= partsCount) {
addMessage('Файл "'+file.name+'" загружен');
}
}
});
pos += upload_chunk_size;
}
}