js下载远程图片

转换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)) ? (<spanonClick={() => {fetch(`${downloadSourcePath}${file}`).then(res => res.blob()).then(res => downloadBlob(res, file));}}>下载</span>) : (<a href={`${downloadSourcePath}${file}`} download={file}>下载</a>)}</>

本文链接:https://my.lmcjl.com/post/7317.html

展开阅读全文

4 评论

留下您的评论.