Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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==');

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading