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

168
Views
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 answers
Answer question

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 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!