繁体   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