
Take note, this trick may not work on all browsers – Some may not allow click() on a link due to security settings. Yes, this sets a base 64 encoded data URL to it.
(B2) The magic happens when we do anchor.href = canvas.toDataURL(MIME-TYPE). (B2) Set the “download as” filename – anchor.download = "image.png". (B2) We create an HTML anchor link in Javascript – var anchor = document.createElement("a"). This is pretty much doing the same stuff in the introduction snippet, but packaged into a function for your convenience: (B4) SAFER ALTERNATIVE - LET USER CLICK ON LINK Let anchor = document.createElement("a") Īnchor.href = canvas.toDataURL("image/" + type) If you want to automate this task for your website screenshots, let Stillio do the heavy lifting.Let canvas = document.getElementById(target) You even get the niceties of overcoming the dreaded CORS error. If you're already calling a Node.js back-end to feed your front-end, why not add an endpoint to help you download remote images with a better experience. If you're working with large images, consider a static solution. AWS limits the size of request bodies to ~6MB. If you're using a serverless solution, be mindful of their Request Payload size limits. This simply takes the data in the result body and feeds it into the body of the response to the client. image/png for the content-type header and file extension to be accurate. Note here too you might want to have some sort of library or checker to determine the image MIME type e.g. Setting the appropriate headers for the response:Ĭontent-dispostion with a value of attachment will tell the browser to save the file instead of the alternative inline which will try to render the response in the browser.
Instead of making a fetch directly to the image, you will make it to your Node.js API endpoint, which could be set up as follows: The following example only requires one simple change to the download logic on the client - the URL. a Node.js server - CORS can be safely bypassed. Luckily, for requests not coming from a browser e.g. Making image download robust with Node.js CORS or Cross-Origin Resource Sharing may many times cause the download to fail from the browser if the resource is not on the same origin, or doesn't have the appropriate headers set. This experience may be more user-friendly, but don't be surprised if you run into the notorious CORS wall.
Because the anchor tag has an object URL, the browser will initiate the download to the user's Download Folder. The client-side code above listens to a click on the HTML button, fetches the image as a blob, creates an objectURL, adds it to a newly created (hidden) anchor tag and clicks it to initiate a download. Enter fullscreen mode Exit fullscreen mode