I need to upload multiple images that are inside my application.
My form is this:
<form id="uploadForm" enctype="multipart/form-data">
<div class="file-field input-field offset-s4">
<div class="btn gradient-45deg-blue-indigo">
<span id="total" >Arquivo(s)</span>
<input type="file" id="file" name="Imagem" />
</div>
<div class="file-path-wrapper">
<input id="fileUpload" class="file-path validate" type="text" placeholder="Escolha um ou mais imagens">
</div>
</div>
<div class="demo-container center">
<img id="list" class="materialboxed responsive-img" src="" alt="">
</div>
<img id="list2" class="materialboxed responsive-img center" src=""></img>
<p id="imgvalor" class="center"></p>
<button onclick="nuvem()" class="btn btn-success waves-effect waves-light gradient-45deg-blue-indigo" id="enviar" name="action">Nuvem<i class="mdi mdi-cloud-upload left"></i></button>
</form>
This is my array of images:
elemento=[
'assets/cf10/f10d1.jpg',
'assets/cf20/f20d1.jpg',
'assets/cf30/f30d1.jpg',
'assets/cf40/f40d1.jpg',
'assets/cf50/f50d1.jpg'
]
After having my array, I use this function to transform the images into base64:
const toDataURL = url => fetch(url)
.then(response => response.blob())
.then(blob => new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result)
reader.onerror = reject
reader.readAsDataURL(blob)
}))
Then I call the function that will change the image in my html tag:
var imgmudar =
toDataURL(elemento[2])
.then(dataUrl => {
document.getElementById('list').src = dataUrl;
})
Now that I have the image loaded into the DOM, I can use my function that does a local rendering:
var tempototloc;
function tempoLocal() {
var fim = new Date().getTime();
var tempo = fim - inicio;
var d = new Date();
tempototloc = tempo;
document.getElementById('TempoExec').value = tempo +' ms';
document.getElementById('OndeProc').value = 'Local';
document.getElementById('DataExec').value = d.getDate() +'/'+ (d.getMonth()+1)+'/'+d.getFullYear()+' '+d.getHours()+':'+d.getMinutes()+':'+d.getSeconds();
$('#enviarDados').ajaxForm({
url:'/enviar/dados',
type:'post',
success: function(data){
}
}).submit();
swal('Foram encontradas '+contface+ ' face(s)', 'O tempo Local foi de '+tempototloc+' ms', 'success');
}
var inicio;
var contface = 0;
function local() {
inicio = new Date().getTime();
(function(){
var img = document.getElementById('list');
var tracker = new tracking.ObjectTracker(['face']);
tracker.setStepSize(1.7);
tracking.track('#list', tracker);
var face = [];
var i = 0;
tracker.on('track', function(event) {
event.data.forEach(function(rect) {
window.plot(rect.x, rect.y, rect.width, rect.height);
i++;
face[i] = rect.x + '-' +rect.y;
});
document.getElementById('contar').innerHTML = i+' faces encontradas';
contface = i;
});
window.plot = function(x, y, w, h) {
var rect = document.createElement('div');
document.querySelector('.demo-container').appendChild(rect);
rect.classList.add('rect');
rect.style.width = w + 'px';
rect.style.height = h + 'px';
rect.style.left = (img.offsetLeft + x) + 'px';
rect.style.top = (img.offsetTop + y) + 'px';
};
}());
setTimeout(tempoLocal, -1);
}
$('#file').click(function(){
$('.rect').removeAttr('style');
$('#imgvalor').html("");
});
At this point, okay, the problem is when I submit the form to the server, the image is not read (I do not know if I'm using an input type="file") because when I manually load the image I can perform the function below, but when I make this change of the image through the previous functions does not work, it is as if I did not load this information somewhere for the form to send to the server.
My send function to the server is this:
var time1 = 0;
var time2 = 0;
var contfaceserv = 0;
function serverdet(){
$('#uploadForm').ajaxForm({
url:'/upload',
type:'post',
success: function(data){
$('#imgvalor').html(data.msg);
$('#list').attr('src', data.file);
$('#contar').html(data.qtdface);
$('#faces').html(data.arrface);
contfaceserv = data.qtdface;
dadosnuvem();
}
});
}
function dadosnuvem(){
time2 = new Date().getTime();
var time3 = time2 - time1;
var d = new Date();
document.getElementById('TempoExec').value = time3 +' ms';
document.getElementById('OndeProc').value = 'Nuvem';
document.getElementById('DataExec').value = d.getDate() +'/'+ (d.getMonth()+1)+'/'+d.getFullYear()+' '+d.getHours()+':'+d.getMinutes()+':'+d.getSeconds();
$('#enviarDados').ajaxForm({
url:'/enviar/dados',
type:'post',
success: function(data){
}
}).submit();
swal('Foram encontradas '+contfaceserv+ ' face(s)', 'O tempo na Nuvem foi de '+time3+' ms', 'success');
}
function nuvem(){
time1 = new Date().getTime();
serverdet();
}
I also have this function that reads the file when the event is performed in the file:
(function() {
function handleFileSelect(evt) {
let files = evt.target.files; // Lista de Arquivos
// Laço para pegar lista de arquivos e renderizar os Previews
for (var file of files) {
// Somente irá processar se for imagem
if (!file.type.match('image.*')) {
continue;
}
var imagem = new Image(); //Instancia do Objeto Image acessar imagens
var reader = new FileReader(); //Instancia do FileReader acessar arquivos
// Função para percorrer informações dos arquivos
reader.onload = (function(theFile) {
// Renderizando Previews
imagem.src = theFile.target.result;
//var span = document.createElement('span');
var nome = '${theFile.target.result}';
var output = [];
imagem.onload = function() {
var height = this.height,
width = this.width;
document.querySelector('.arquivo').innerHTML = '<ul>${file.type || 'n/a'}</ul>';
document.querySelector('.tamanho').innerHTML = '<ul>${file.size+' bytes' || 'n/a'}</ul>';
document.querySelector('.dimensao').innerHTML = '<ul>${width}x${height}</ul>';
document.getElementById('TipoStatus').value = file.type ? file.type : 'n/a';
document.getElementById('TamStatus').value = file.size ? file.size + ' bytes' : 'n/a';
document.getElementById('DimStatus').value = width +'x'+height;
let result = '<li><b> - bytes - </b>';
//document.getElementById('#list').insertBefore(span, null);
document.getElementById('list').src = nome;
}
});
// Ler arquivo da imagem com uma URL.
reader.readAsDataURL(file);
}
}
document.getElementById('file').addEventListener('change', handleFileSelect, true);
}());
I know that my code is messed up, but I need to automate this sending process, because manually, although it can be very time-consuming.
I saw the use of promisses, but I'm not sure how to mount logic in a synchronic way (image1 -> local () and then cloud () - > image 2 ...) , by I'm trying to do this by using an array of the images and then calling the local () function and another () cloud for each image I have in my array list. How do I accomplish the feat of loading the image, and call my functions for each one?