我在按钮上放置了一个很长的 Google Cloud 存储 URL。因此,当用户单击此按钮时,它应该直接下载 URL。我不想在新选项卡中打开该 URL。
网址看起来像这样 -
https://storage.googleapis.com/{BUCKET NAME}/FILENAME.pdf?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=&X-Goog-Date=&X-Goog-Expires=&X-Goog-SignedHeaders=host&X-Goog-Signature=
HTML5不允许直接下载不同来源的资源(不在同一个域的资源)。
换句话说,https://yourdomain.com 无法使用 HTML 锚标记从 https://google.com 下载文件。
一种解决方法是获取资源,将其转换为 blob,然后将 href 设置为 blob URL。
这里有一个代码参考,可以做到这一点:
/**
* Modern browsers can download files that aren't from same origin this is a workaround to download a remote file
* @param `url` Remote URL for the file to be downloaded
*/
function Download({ url, filename }) {
const [fetching, setFetching] = useState(false);
const [error, setError] = useState(false);
const download = (url, name) => {
if (!url) {
throw new Error("Resource URL not provided! You need to provide one");
}
setFetching(true);
fetch(url)
.then(response => response.blob())
.then(blob => {
setFetching(false);
const blobURL = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = blobURL;
a.style = "display: none";
if (name && name.length) a.download = name;
document.body.appendChild(a);
a.click();
})
.catch(() => setError(true));
};
return (
<button
disabled={fetching}
onClick={()=> download(url, filename)}
aria-label="download gif"
>
DOWNLOAD
</button>
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
您可以在这里了解更多信息: