Following code snippet fetches the image from an URL and converts the blob to a base64 string before saving the file to the file system. (Saving the file to the file system can be considered being additional boilerplate as a conversion from a blob to a base64 string is not needed to save a file to the file system. See second example.)
The code snippets shows how to:
- download an image from a server
- convert image to a base64 string
/**
* Fetches an image from given URL.
*
* @param {string} url - url providing the image
* @return {Promise<Blob>} fetched blob
*/
async function fetchImage(url) {
const response = await fetch(url);
return await response.blob();
}
/**
* Downloads given blob as file using given file name.
* Converts a blob to a Base64 string.
*
* @param {Blob} blob - blob object
* @return {Promise<string>} the Base64 string
*/
async function blobToBase64(blob) {
return new Promise((resolve, _) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.readAsDataURL(blob);
});
}
/**
* Downloads given Base64 string as file using given file name.
*
* @param {string} fileName - file name
* @param {string} base64String - a valid Base64 string
*/
function saveAs(fileName, base64String) {
const element = document.createElement("a");
element.setAttribute("href", base64String);
element.setAttribute("download", fileName);
element.style.display = "none";
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
const url = "....";
fetchImage(url)
.then(blob => blobToBase64("image.jpg", blob));
.then(base64String => saveAs("image.jpg", base64String));
/**
* Fetches an image from given URL.
*
* @param {string} url - url providing the image
* @return {Promise<Blob>} fetched blob
*/
async function fetchImage(url) {
const response = await fetch(url);
return await response.blob();
}
/**
* Downloads given blob as file using given file name.
*
* @param {string} fileName - file name
* @param {blob} blob - blob
*/
export function saveBlobAs(fileName, blob) {
const element = document.createElement("a");
element.setAttribute("href", URL.createObjectURL(blob));
element.setAttribute("download", fileName);
element.style.display = "none";
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
const imageUrl = "https://geomo.ch/img/peggys-cove-thumbnail-reduced.jpg";
fetchImage(imageUrl)
.then(blob => saveBlobAs("image.jpg", blob));