解决:js 根据图片链接(image url)下载,有的打开预览,有的下载
1、问题描述
https://*****/drugTestReport/20230515/202305151106111386737.png
https://*****/drugTestReport/20230605/202306051540314553141.jpg
同样结构的两个图片链接,使用window.open(url),一个是打开预览,另一个是下载
2、解决方法,通过fetch请求url,获取blob类型,区分情况,统一成下载。
/** * ### 适合预览操作的 Blob 类型,需要将链接地址字符内容转变成blob地址 - image/png - image/jpeg - image/gif - audio/mpeg - audio/ogg - audio/wav - video/mp4 - video/ogg ### 适合下载操作的 Blob 类型 - text/plain - text/csv - application/pdf - application/json - application/xml - application/zip - application/octet-stream */ async function downloadImg(url) { try { const res = await fetch(url); if (!res.ok) { throw new Error("fetch network response was not ok"); } const blob = await res.blob(); if ( blob.type.includes("image") || blob.type.includes("audio") || blob.type.includes("video") ) { const a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = ""; document.body.appendChild(a); a.click(); } else { window.open(url); } } catch (error) { //有些图片url请求本身就出现了跨域等问题,目前纯前端本人还无解,只能直接open console.log("catcherror", err); window.open(url); } }