1、問題描述
https://*****/drugTestReport/20230515/202305151106111386737.png
https://*****/drugTestReport/20230605/202306051540314553141.jpg
同樣結(jié)構(gòu)的兩個(gè)圖片鏈接,使用window.open(url),一個(gè)是打開預(yù)覽,另一個(gè)是下載
?
2、解決方法,通過fetch請(qǐng)求url,獲取blob類型,區(qū)分情況,統(tǒng)一成下載。文章來源:http://www.zghlxwxcb.cn/news/detail-483804.html
/** * ### 適合預(yù)覽操作的 Blob 類型,需要將鏈接地址字符內(nèi)容轉(zhuǎn)變成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請(qǐng)求本身就出現(xiàn)了跨域等問題,目前純前端本人還無解,只能直接open console.log("catcherror", err); window.open(url); } }
?文章來源地址http://www.zghlxwxcb.cn/news/detail-483804.html
到了這里,關(guān)于解決:js 根據(jù)圖片鏈接(image url)下載,有的打開預(yù)覽,有的下載的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!