Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

217
Views
Convierta cada entrada de imagen a imagen DataUrl o Base64 mientras itera
var toPush = [] for(var i = 1; i <= myVariable; i++){ var variable1 = document.getElementById('q' + i).value; var var2 = document.getElementById(i + 'x').value; var var3 = document.getElementById(i + 'y').value; var var4 = document.getElementById(i + 'z').value; var var5 = document.getElementById(i + 'd1').value; var var6 = document.getElementById('xy' + i).value; var file = document.getElementById("fileup" + i); var twofour = [var2, var3, var4, var5]; let reader = new FileReader(); reader.readAsDataURL(file.files[0]); reader.onload = function () { pictureURL = reader.result; }; reader.onerror = function (error) { console.log('Error: ', error); }; toPush.push({"variable1": variable1, "twofour": twofour, "pictureURL": pictureURL} }

La aplicación puede agregar X muchas entradas agregándolas a div. Cuando se trata de enviar los datos, quiero que la entrada del archivo , que es la única entrada de imagen, se lea como DataURL, de modo que pueda usarse como fuente para una vista previa de la imagen. No sé si es por la iteración, pero la variable pictureURL aparece como vacía: en la base de datos obtuve "pictureURL": "".

¿Hay alguna manera de evitarlo?

Gracias de antemano.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Hay varios problemas con este código. La razón por la que no está recibiendo la pictureUrl de la imagen es porque la está leyendo antes de que esté lista.

FileReader lee el archivo de forma asíncrona. Nos proporciona una onload de devolución de llamada que se ejecuta cuando ha leído el archivo. Obtenemos el contenido del archivo como reader.result solo cuando se ejecuta esta devolución de llamada. Tiene que reescribir su código para procesar el contenido del archivo cuando se FileReader.onload o FileReader.onerror .

Vea el ejemplo de trabajo a continuación. He eliminado código innecesario. Puede ejecutar el código haciendo clic en el botón Run code snippet en la parte inferior de la publicación

 function showIcons() { let files = document.querySelector('#files').files; if(files.length) { document.querySelector('#show-icons-error').textContent = ""; } else { document.querySelector('#show-icons-error').textContent = 'No files have been selected'; } let imageIcons = document.querySelector('#image-icons'); imageIcons.innerHTML = ''; let imageUrlArr = []; for(var i = 0; i < files.length; i++) { let imageIconHolder = document.createElement('img'); imageIconHolder.classList.add('image-icon'); imageIconHolder.setAttribute('image-index', i); imageIcons.appendChild(imageIconHolder); let file = files[i]; let reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function () { pictureURL = reader.result; imageIconHolder.src = pictureURL; imageUrlArr[i] = pictureURL;//Setting ith image, not pushing. }; reader.onerror = function (error) { console.log(`Error loading image at index : ${i}, error: ${error}`); imageUrlArr[i] = error;//Error for ith image }; } }
 .image-icon { width: 10em; display: block; min-height: 5em; }
 <html> <body> <label for="files" class="btn">Select Images</label> <input id="files" type="file" value="Select File" accept="image/*" multiple="multiple"> <br/> <br/> <div> <button id="show-icons" onclick="showIcons()">Show Icons</button> <span id='show-icons-error' style="color: red; font-weight: bold;"></span> </div> <br/> <div id="image-icons"> </div> </body> </html>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!