在我的React应用程序中,我正确地显示和映像(在本例中为SVG),我希望用户可以单击按钮下载它。该图像由Firebase Storage提供。
它不起作用,因为我得到了他CORS错误:
从源http://localhost:3000获取xxxxxxxxx的权限已被CORS策略阻止:对预检请求的响应未通过权限改造检查:请求的资源上不存在Access-Control-Allow-Origin标头。如果不透明的响应满足您的需求,请将请求的模式设置为no-cors以获取禁用CORS的资源。
这是我的代码:
export const Download = () => {
const url = "https://storage.googleapis.com/xxxxxxxxxx-c1d67.appspot.com/KYi5nFkjgJPuIxeDkuzvC8XfP6A3/1673110077807-0.svg?GoogleAccessId=xxxxxxxxxxx"
const handleClickDownload = (fileUrl: string) => {
fetch(fileUrl, {
method: 'GET',
headers: {
'Content-Type': 'application/pdf',
},
})
.then((response) => response.blob())
.then((blob) => {
// Create blob link to download
const url = window.URL.createObjectURL(
new Blob([blob]),
);
const link = document.createElement('a');
link.href = url;
link.setAttribute(
'download',
`filename.svg`,
);
// Append to html link element page
document.body.appendChild(link);
// Start download
link.click();
// Clean up and remove the link
link.parentNode?.removeChild(link);
});
}
return (
<div>
<img src={url} alt='result' />
<button onClick={() => handleClickDownload(url)}>Download SVG</button>
</div>
)
};
如下所述CORS必须启用Firebase存储:
Firebase存储和访问-控制-允许-来源