Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

163
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda