0

I have a function in my web app that allows me to download a present image. What I would also like it to do is give me the opportunity to save this file under the name upon download.

My function is this:

 function saveFile(){
      var dataURL = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); 
      console.log(dataURL);
      window.location.href = dataURL; 
    }

And how can I do to name this file? Thank u all!

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
  • Does this answer your question? [File download - How can I control the filename AND respect the users preferences?](https://stackoverflow.com/questions/55828475/file-download-how-can-i-control-the-filename-and-respect-the-users-preferences) – Daniel Stoyanoff May 13 '21 at 12:42

1 Answers1

-1

First create anchor tag and add href and download attribute to provide the uri and fileName respectively.

function saveFile(){
      var dataURL = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); 
      console.log(dataURL);
      const anchorLink = document.createElement('a');
      document.body.appendChild(anchorLink)
      anchorLink.href = dataURL;
      anchorLink.download = "file_name.png"; 
      anchorLink.click();
      document.body.removeChild(anchorLink)
}
Rahul Kumar
  • 3,009
  • 2
  • 16
  • 22
  • The `location` object isn't an anchor element. It doesn't have a `download` property. https://developer.mozilla.org/en-US/docs/Web/API/Window/location – Quentin May 13 '21 at 12:47