JavaScript Snippet – Download Picture/Video
There are a couple of ways to download media assets on the web. One of them involves making an HTTP
request to the location of the media asset and using JavaScript inbuilt methods to manipulate the asset.
<button onclick="downloadImage()">Download Image</button>
To get started, we add a button to our markup that would trigger the download. We add an onclick
listener to the button that calls the download method.
function downloadImage() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://via.placeholder.com/150', true);
xhr.responseType = 'blob';
xhr.onload = function() {
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
var tag = document.createElement('a');
tag.href = imageUrl;
tag.target = '_blank';
tag.download = 'sample.png';
document.body.appendChild(tag);
tag.click();
document.body.removeChild(tag);
};
xhr.onerror = err => {
alert('Failed to download picture');
};
xhr.send();
}
In the script section, we define the downloadImage()
method. Here we are using XHLHttpRequest
but you can use fetch
or any other http
library. Here, we’ll be downloading an image so we pass in the URL. We specify a response type of blob
. .createObjectUrl()
creates a temporary URL with the response. Then we create an a
tag and assign the href
attribute with the temporary URL. We set the download attribute to the name of the image (sample.png in this case but you can give it any other name). Finally, we attach the link to the document’s body and trigger a click event on it with JavaScript. This would prompt the user to save the downloaded image.
NB: This technique only works if the script and image/video are on the same server.
Use Cases
- Downloading pictures
- Downloading videos