Показать сообщение отдельно
  #1 (permalink)  
Старый 10.03.2014, 11:14
Новичок на форуме
Отправить личное сообщение для Ruslan1802 Посмотреть профиль Найти все сообщения от Ruslan1802
 
Регистрация: 16.02.2014
Сообщений: 6

Загрузчик файлов на js
Всем добрый день, прошу помощи. Дело в том, что в месте, где выполняется цикл $.each() cначала запускаются функции, а потом выполняется их код одновременно. Но если так, то у меня создается несколько потоков, чего мне не надо, так как собираюсь отправлять файлы по очереди. Если я правильно понимаю, нужно проверить, завершила ли функцию свою работу, а уже тогда дальше выполнять цикл. Но как это cделать, я не знаю.

$(document).ready(function(){




$('#upload a').click(function(e){
$(this).parent().find('input[type="file"]').click();
e.preventDefault();
});

$('#upload input[type="file"]').change(function() {
     uploadFile(this.files);
	 $(this).val('');
});


var files_mas = new Array();
var maxSize = 1000000000000000; //max размер файла

var server = $('#upload').attr('action');
var file_server = $('#upload input[type="file"]').attr('name'); //имя пост запроса



function uploadFile(files) {

$.each(files, function(index, file) { 
if (file.size < maxSize) { 

 files_mas.push(file);
$('#status').append('<div class="progress progress-striped active" id="'+files_mas.length+'"><div class="progress-bar"  role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" style="width: 0%"><span class="sr-only">45% Complete</span></div></div><div class="status"></div>');
   }
	else
	{
alert('Слишком большой файл');
}
});
		
		
}

var req = new XMLHttpRequest();
var form = new FormData(); // Создаем объект формы.

function add_s(index, file) {
req.open('POST', 'upload.php', true); // Открываем коннект до сервера.
form.append('upload', file);

var i = index + 1;


req.upload.onprogress = function(e) {
var percent = 0;
var position = e.loaded || e.position;
var total = e.total || e.totalSize;
if(e.lengthComputable){
percent = Math.ceil(position / total * 100);

$('#'+i+'> div').attr('style', 'width: '+percent+'%').text(percent+'%');
if(percent == 100) {
alert('ФАЙЛ | ' + file.name + ' | УСПЕШНО ЗАГРУЖЕН!!!');
files_mas.length = files_mas.length - 1;
alert(files_mas.length);
$('#'+i).remove();   

}

}

	
} 


req.onreadystatechange = function () {
            
            if (this.readyState == 4) { 
                if(this.status == 200) { 	

alert(req.responseText);

                } else {
                    alert('error');
                }

            }

        }


req.send(form); 


} 

$('#upload').submit(function(e) { 
e.preventDefault(); 

$.each(files_mas, function(index, file) {

add_s(index, file);

});
});


});

<style type="text/css">
#upload > input[type="file"] { display:none; }
</style>
</head>
<body>

<form id="upload" method="post" action="upload.php" enctype="multipart/form-data">
<a href="#">Прикрепить файлы</a>
<input type="file" name="upload[]" multiple />
<br>
<br>
<input type="submit" value="Загрузить" class="btn" >
</form>
Ответить с цитированием