Created
November 22, 2016 19:47
-
-
Save abler98/54eb7f0638e31c093ef296d1c9c2342e to your computer and use it in GitHub Desktop.
Uploading files to server with queues
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Загружает файл на сервер | |
*/ | |
var requestQueue = [], | |
sendingRequest = false; | |
window.attachRequestToQueue = (queue) => { | |
requestQueue.push(queue); | |
doRequestQueue(); | |
}; | |
window.doRequestQueue = () => { | |
if (!sendingRequest && requestQueue.length > 0) { | |
var queue = requestQueue.shift(); | |
queue().always(function () { | |
sendingRequest = false; | |
doRequestQueue(); | |
}); | |
sendingRequest = true; | |
} | |
}; | |
window.uploadImageFile = (file, callback) => { | |
var url = window.Laravel.uploadImageUrl; | |
var data = new FormData(); | |
data.append('photo', file); | |
var action = (data64) => { | |
var progress = [ | |
'<div>Идёт загрузка изображения</div>', | |
'<div class="progress progress-striped active" style="margin-top: 5px">', | |
' <div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 100%"></div>', | |
'</div>' | |
].join(''); | |
var text = [ | |
'<div class="row">', | |
' <div class="col-md-3"><img class="img-responsive img-thumbnail" src="' + data64 + '"></div>', | |
' <div class="col-md-9">' + progress + '</div>', | |
'</div>' | |
].join(''); | |
var queue = () => { | |
var uploadNotify; | |
var request = $.ajax({ | |
url: url, | |
method: 'POST', | |
data: data, | |
success: callback, | |
beforeSend: function () { | |
uploadNotify = new PNotify({ | |
title: 'Загрузка изображения', | |
text: text, | |
type: 'info', | |
nonblock: { | |
nonblock: true | |
}, | |
styling: 'bootstrap3' | |
}); | |
}, | |
complete: function () { | |
uploadNotify.remove(); | |
}, | |
error: function (xhr) { | |
new PNotify({ | |
text: 'Ошибка загрузки файла', | |
type: 'error', | |
styling: 'bootstrap3' | |
}); | |
}, | |
contentType: false, | |
processData: false, | |
}); | |
return request; | |
}; | |
attachRequestToQueue(queue); | |
}; | |
var reader = new FileReader(); | |
reader.addEventListener('load', function (e) { | |
action(e.target.result); | |
}.bind(this)); | |
reader.readAsDataURL(file); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment