Home > Net >  Download a PNG file that was uploaded via an input field
Download a PNG file that was uploaded via an input field

Time:01-15

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

CodePudding user response:

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.

  •  Tags:  
  • Related