简体   繁体   中英

how to save file with name in a download function with javascript?

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM