使用 ReactJS+semantic-ui-react 下载文件
Downloading a file using ReactJS+semantic-ui-react
我有这种情况,点击一个按钮,我发出一个获取请求,它会给我一个 url 需要下载的文件。我怎样才能达到同样的效果?
Fetch API 会给我 link 一个需要下载的文件
不胜感激
<Button
fluid={false}
size={"small"}
onClick={this.download}
>
Download
</Button>
download = async () => {
try {
let response = await fetch('/fetch/downloadurl');
let json = await response.json();
let url = json.url;
// Need to write the download code here
window.open(url); // not working
} catch (error) {
console.log(error);
}
};
有多种解决方案,但它们依赖于 HTML5,并且尚未在某些浏览器中完全实现。下面的示例在 Chrome 和 Firefox 中进行了测试(部分有效)。
- 只需将 document.location.href 设置为数据 URI。
<a href="your-data-uri" download="filename.txt">
您最好可以使用 Downloadify javascript 库 (https://github.com/dcneiner/Downloadify) 这适用于所有浏览器
试试这个答案:
function download(url, name) {
var link = document.createElement('a');
link.download = name;
link.href = url;
link.click();
}
我有这种情况,点击一个按钮,我发出一个获取请求,它会给我一个 url 需要下载的文件。我怎样才能达到同样的效果?
Fetch API 会给我 link 一个需要下载的文件
不胜感激
<Button
fluid={false}
size={"small"}
onClick={this.download}
>
Download
</Button>
download = async () => {
try {
let response = await fetch('/fetch/downloadurl');
let json = await response.json();
let url = json.url;
// Need to write the download code here
window.open(url); // not working
} catch (error) {
console.log(error);
}
};
有多种解决方案,但它们依赖于 HTML5,并且尚未在某些浏览器中完全实现。下面的示例在 Chrome 和 Firefox 中进行了测试(部分有效)。
- 只需将 document.location.href 设置为数据 URI。
<a href="your-data-uri" download="filename.txt">
您最好可以使用 Downloadify javascript 库 (https://github.com/dcneiner/Downloadify) 这适用于所有浏览器
试试这个答案:
function download(url, name) {
var link = document.createElement('a');
link.download = name;
link.href = url;
link.click();
}