首页 > 其他分享 >js下载远程图片

js下载远程图片

时间:2023-02-19 10:32:32浏览次数:50  
标签:const string res js blob file 远程 下载


a标签的download属性无法下载远程图片 可以将图片转换成 blob 然后下载

<a href="https://xxxx.xxx/xxxx.png" download="xxx.png"> 下载 </a>

转换blob下载

/**
* blob文件下载
* @param {Blob} blob
* @param {string} fileName
* @return {*} void
*/
export const downloadBlob = (blob: Blob, fileName: string) => {
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = fileName;
a.click();
URL.revokeObjectURL(url);
};

fetch("image url")
.then(res => res.blob())
.then(res => downloadBlob(res, file));

体验地址 我的网站 欢迎来访
​​​http://hongbin.xyz/sourceSquare​


相关代码

/**
* 获取文件拓展名 123.png -> .png | ""
* @param {string} path
* @return {string} ext
*/
export const getExt = (path: string): string => {
const split = path.match(/\w+(\.\w+)$/);
return split ? split[1] : "";
};

/**
* 常见的图片后缀名数组
*/
export const imageExt = [".gif", ".png", ".jpg", ".jpeg", ".avif", ".webp"];

react中使用 像 .apk等其他文件可以下载 可以区分后缀名决定是否转换blob下载

return <>
{imageExt.includes(getExt(file)) ? (
<span
onClick={() => {
fetch(`${downloadSourcePath}${file}`)
.then(res => res.blob())
.then(res => downloadBlob(res, file));
}}
>
下载
</span>
) : (
<a href={`${downloadSourcePath}${file}`} download={file}>
下载
</a>
)}
</>


标签:const,string,res,js,blob,file,远程,下载
From: https://blog.51cto.com/u_15964288/6066505

相关文章