This is my code:
function downloadImage(url) {
fetch(url, {
mode: 'no-cors',
})
.then(response => response.blob())
.then(blob => {
let blobUrl = window.URL.createObjectURL(blob);
let a = document.createElement('a');
a.download = url.replace(/^.*[\\\/]/, '');
a.href = blobUrl;
document.body.appendChild(a);
a.click();
a.remove();
})
}
var url = 'https://c4.wallpaperflare.com/wallpaper/203/636/834/minimalism-landscape-digital-
windows-11-hd-wallpaper-preview.jpg';
downloadImage(url)
When I run this code it's download the image successfully but when I open the image it's shows Sorry, Photos can't open this file because the format is currently unsupported, or the file is corrupted Can anyone tell me please why it's happening and how can I fix this issue.
The image url you are using is blocking your request hence you are getting empty blob.
I have tried your code with unsplash image it is working.
async function downloadImage(url) {
try {
const res = await fetch(url);
const blob = await res.blob();
const blobUrl = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.download = url.replace(/^.*[\\\/]/, "");
a.href = blobUrl;
document.body.appendChild(a);
a.click();
a.remove();
} catch (error) {
console.log(error);
}
}
const url =
"https://images.unsplash.com/photo-1644982647844-5ee1bdc5b114?ixlib=rb-1.2.1&ixid=MnwxMjA3fDF8MHxlZGl0b3JpYWwtZmVlZHwxfHx8ZW58MHx8fHw%3D&auto=format&fit=crop&w=500&q=60";
downloadImage(url);