簡體   English   中英

作為用戶從前端下載圖像(我有鏈接)?

[英]Download image (I have the link) from the front-end as user?

我想允許我的用戶下載圖像,我知道如果我有一個文件,我可以使用標簽下載並且它會起作用,但是如果我有鏈接它就不起作用

我已經嘗試過下載標簽,並閱讀了谷歌雲存儲下載對象文檔,但最后一個的問題是它被下載到我的服務器上,我也試圖返回文件,但它只是一個沒有文件的承諾信息

帶下載代碼的前端(不起作用),我用download={preview}試過了

      <div className={classes.fileInputs}>
        <a download href={preview} title="Imagen">
          <img
            src={preview}
            alt='Preview obj'
            className={classes.imgPreview}
          />
        </a>

這就是我認為它應該工作的方式,但它沒有,下載會觸發對后端的請求,但圖像已下載到我的服務器中

<Button color="inherit" onClick={() => download()}>
   Download
</Button>

我只希望單擊下載按鈕將使客戶端擁有其圖像

如果你願意,你可以使用 axios:

axios({
url: 'http://localhost:5000/static/example.jpg',
method: 'GET',
responseType: 'blob', // important
}).then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.jpg');
document.body.appendChild(link);
link.click();
});

您可以在此處查看更多詳細信息

要從 "content-disposition" -header 設置文件類型和文件名,您可以使用:

const blob = new Blob([response.data], {type: response.data.type});

const url = window.URL.createObjectURL(blob);

const link = document.createElement('a');

鏈接.href = url;

const contentDisposition = response.headers['content-disposition'];

讓文件名 = '未知';

如果(內容處置){

const fileNameMatch = contentDisposition.match(/filename="(.+)"/);

if (fileNameMatch.length === 2)

    fileName = fileNameMatch[1];

}

link.setAttribute('下載', 文件名);

document.body.appendChild(link);

鏈接。點擊();

鏈接.remove();

window.URL.revokeObjectURL(url);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM