使用 react-admin 从 API 响应的数据中下载文件
Download file from data of an API response with react-admin
我正在尝试在我的反应管理面板的 AppBar 中创建一个自定义按钮来下载数据库的转储。
API 的响应是 json,其中包含有关请求的信息以及数据库的内容。
如何使用包含数据的 json 字段从客户端开始下载?
我暂时这样做了:
const CustomAppBar = withStyles(styles)(({ classes, ...props }) => {
const dumpDatabase = () => {
fetch(config['api_url'] + '/dump', { method: 'GET' })
.then(data => data.json())
.then((json) => {
console.log(json['data']);
});
}
return (
<AppBar {...props}>
<Typography
variant="inherit"
color="inherit"
className={classes.title}
id="react-admin-title"
/>
<span className={classes.spacer} />
<Tooltip title="Dump Database">
<IconButton color="inherit" onClick={dumpDatabase} >
<SaveIcon />
</IconButton>
</Tooltip>
</AppBar>
);
});
console.log(json['data']);
是我要替换为下载的部分。一般来说,我对 reat-admin 和 javascript 的经验很少...
一段时间后,我找到了一个可以使用的可行解决方案。您必须创建一个 blob 对象并将其分配给 link,然后您通过脚本自动单击它。
dumpDatabase = () => {
fetch(config['api_url'] + '/dump', { method: 'GET' })
.then(data => data.json())
.then(json => {
if (json['result'] === 'success')
{
// Creating the blob file and its url
var blob = new Blob([json['data']], {type: 'application/json'});
let url = window.URL.createObjectURL(blob);
var date = Moment(new Date()).format("YYYY_MM_DD-HH_mm_ss");
// Creating the hyperlink and auto click it to start the download
let link = document.createElement('a');
link.href = url;
link.download = 'dump_' + date + '.json';
link.click();
}
});
}
我正在尝试在我的反应管理面板的 AppBar 中创建一个自定义按钮来下载数据库的转储。 API 的响应是 json,其中包含有关请求的信息以及数据库的内容。
如何使用包含数据的 json 字段从客户端开始下载? 我暂时这样做了:
const CustomAppBar = withStyles(styles)(({ classes, ...props }) => {
const dumpDatabase = () => {
fetch(config['api_url'] + '/dump', { method: 'GET' })
.then(data => data.json())
.then((json) => {
console.log(json['data']);
});
}
return (
<AppBar {...props}>
<Typography
variant="inherit"
color="inherit"
className={classes.title}
id="react-admin-title"
/>
<span className={classes.spacer} />
<Tooltip title="Dump Database">
<IconButton color="inherit" onClick={dumpDatabase} >
<SaveIcon />
</IconButton>
</Tooltip>
</AppBar>
);
});
console.log(json['data']);
是我要替换为下载的部分。一般来说,我对 reat-admin 和 javascript 的经验很少...
一段时间后,我找到了一个可以使用的可行解决方案。您必须创建一个 blob 对象并将其分配给 link,然后您通过脚本自动单击它。
dumpDatabase = () => {
fetch(config['api_url'] + '/dump', { method: 'GET' })
.then(data => data.json())
.then(json => {
if (json['result'] === 'success')
{
// Creating the blob file and its url
var blob = new Blob([json['data']], {type: 'application/json'});
let url = window.URL.createObjectURL(blob);
var date = Moment(new Date()).format("YYYY_MM_DD-HH_mm_ss");
// Creating the hyperlink and auto click it to start the download
let link = document.createElement('a');
link.href = url;
link.download = 'dump_' + date + '.json';
link.click();
}
});
}