How do I change input type="file" path and send form with another image?

Asked

Viewed 343 times

1

I need to upload several images that are within 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 image array:

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 turn 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 in the DOM, I can use my function that does a local processing:

    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("");
        });

So far, okay, the problem is when I submit the form to the server, the image is not read (I do not know if because I am using an input type="file") because when I load the image manually 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 have not loaded somewhere this information to the send form to the server.

My server upload function 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 perform the reading of the file while being held the event 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 my code is messed up, but I need to automate this sending process, because manually it ends up being very time consuming.

I saw the use of Prs, but I’m not able to assemble the logic in a specific way (imagem1 -> local() and then cloud() -> image 2...), so I’m trying to do it 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 can I accomplish the feat of carrying the image, and calling my duties to each of them?

  • If I used a right select to change the image to be used, could I do my job? Because since I’m using input="file" maybe it needs the manual choice event to store in memory to send (I suppose).

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.