Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

164
Vistas
Download a PNG file that was uploaded via an input field

I uploaded a file via

<input> id="pdf" type="file"></input>

I can access it's content via

var inp = document.querySelector("#pdf");
var text = await inp.files[0].text()

When calling my download function I get "Failed - Network error" (Chromium) and in Firefox nothing happens (function returns undefined).

download("viainput.png",text);

But I struggle to save the same file to the file system, I always get corrupted files. My next step would be to send it to another user via webrtc as encoded text

function download(filename, text) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:image/png;base64,' + encodeURIComponent(text));
  element.setAttribute('download', filename);
 
  element.style.display = 'none';
  document.body.appendChild(element);
 
  element.click();
 
  document.body.removeChild(element);
}
 
// Start file download.
download("hello.png",'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==');
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your current solution doesn't work because you provide URL-encoded data in a string that should be base64-encoded. But forget about that. data: URLs are mostly a thing of the past (or should be).

The efficient way to do this is to not encode the image into a string. Instead, directly use the File you get from the input.

var file = inp.files[0] // this is what you use
// as second argument for `download`

function download(filename, blob) {
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)
  link.href = url
  link.download = filename
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url) // if you're done with that file
}

You can also send the file (which is a Blob by prototype) directly into a WebRTC data channel, then on the other side, create the object URL from the received Blob.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda