[英]Download image from a third-party server button
在任何瀏覽器中,如果您看到圖像,可以右鍵單擊它並單擊“另存為”以下載它。
我正在嘗試制作一個按鈕來下載圖像
下載按鈕應該下載上面的圖像,條形碼。
我正在使用反應,不確定這是否與答案有關。
我讀到你可以使用帶有download
屬性的<a/>
標簽,但是,我在 Firefox 上,它將我重定向到托管條形碼圖像的頁面,而不是打開下載 window:
代碼非常簡單,如下所示:
<a href='https://barcode.tec-it.com/barcode.ashx?data=${product.barcode}&code=&multiplebarcodes=true&backcolor=%23ffffff&quietzone=10&quietunit=Px&size=Small' download>click me</a>
來自 MDN 文檔:
下載僅適用於同源 URL,或 blob: 和 data: 方案。
我想實現這個,我該怎么做? 我不是托管圖像的服務器的所有者。
我們可以在 2023 年做到嗎?
其他問題是混合使用本地圖像和托管在其他服務器上的圖像。 所以我想我可以為只對第三方服務器上的圖像感興趣的人創建這個線程。 - 所以我們這里都是前端,沒有后端相關的東西。
我認為你的問題是指這個老問題。
您需要在服務器上發送 Content-Disposition header 以將文件設置為附件,以便瀏覽器不會嘗試在內部處理該文件。
請參閱: 點擊 href 圖片鏈接下載
它僅適用於同一網站,不適用於外部鏈接。 嘗試使用同一網站的圖像。 例如: <a href="images/detailed-product.png" download>click</a>
您需要代理請求以避免 CORS 問題。 正如文章所述,最好部署自己的代理,但您可以使用免費代理進行測試,例如: https://codetabs.com/cors-proxy/cors-proxy.html
const downloadButton = document.querySelector('button'); downloadButton.onclick = () => { console.log('download button clicked'); downloadImage( 'https://api.codetabs.com/v1/proxy?quest=https://barcode.tec-it.com/barcode.ashx?data=${product.barcode}&code=&multiplebarcodes=true&backcolor=%23ffffff&quietzone=10&quietunit=Px&size=Small' ); }; async function downloadImage(imageSrc) { try { const image = await fetch(imageSrc); const imageBlob = await image.blob(); const imageURL = URL.createObjectURL(imageBlob); const link = document.createElement('a'); link.href = imageURL; link.download = 'image.jpg'; document.body.appendChild(link); link.click(); document.body.removeChild(link); } catch (error) { console.log(error); } }
<button>Download image</button>
為此,您可以使用 URL 中的createObjectURL
URL
方法為圖像創建下載鏈接。 然后,我們在變量中創建臨時<a>
以編程方式打開該鏈接。
async function downloadImage(imageSrc) {
const image = await fetch(imageSrc)
const imageBlob = await image.blob()
const imageURL = URL.createObjectURL(imageBlob)
const link = document.createElement('a')
link.href = imageURL
link.download = 'myimage.jpg'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.