【发布时间】:2015-09-21 18:14:21
【问题描述】:
我正在构建一个带有 ReactJS 前端的应用程序,该前端连接到 Express API 服务器。使用 Ajax 调用 API。
在我的一个视图中,表格的每一行都加载了“导出”链接。导出链接指向一个调用 API 端点的 React 路由,该端点提供 CSV 文件以供下载。
如果我直接使用有效请求(在 React 应用程序之外)访问 API 端点,则会在我的浏览器中启动文件下载。完美的!但是,从 React 页面点击 Export 链接会尝试加载调用 API 的视图。表格从视图中消失并被文件内容替换(目的是为了证明我有数据)但没有下载文件。
我可以强制将响应对象的内容下载为文件吗? 这会发生在 ajax 成功回调中吗? 我尝试使用 javascript,但我在 React 虚拟 DOM 上苦苦挣扎…… 我想这一定很简单,但我很难过。
编辑:@Blex 的评论帮助我解决了这个问题!解决方案添加到代码sn -p...
这是接收数据的 JSX:
module.exports = React.createClass({
mixins: [Router.State],
getInitialState: function() {
return {
auth: getAuthState(),
export: [],
passedParams: this.getParams()
};
},
componentDidMount: function(){
$.ajax({
type: 'GET',
url: ''+ API_URL +'/path/to/endpoint'+ this.state.passedParams.id +'/export',
dataType: 'text',
headers: {
'Authorization': 'Basic ' + this.state.auth.base + ''
},
success: function (res) {
// can I force a download of res here?
console.log('Export Result Success -- ', res);
if(this.isMounted()){
console.log('Export Download Data -- ', res);
this.setState({export: res[1]});
// adding the next three lines solved my problem
var data = new Blob([res], {type: 'text/csv'});
var csvURL = window.URL.createObjectURL(data);
//window.open(csvURL);
// then commenting out the window.open & replacing
// with this allowed a file name to be passed out
tempLink = document.createElement('a');
tempLink.href = csvURL;
tempLink.setAttribute('download', 'filename.csv');
tempLink.click();
}
}.bind(this),
error: function (data) {
console.log('Export Download Result Error -- ', data);
}
});
},
render: function(){
console.log('exam assignment obj -- ', this.state.passedParams.name);
var theFileContents = this.state.export;
return(
<div className="row test-table">
<table className="table" >
<tr className="test-table-headers">
{theFileContents} // this loads the contents
// can I auto download theFileContents?
</tr>
</table>
</div>
)
}
});
【问题讨论】:
-
你可以这样:jsfiddle.net/8f2ah406这里唯一的问题是文件名和扩展名需要在提示时手动设置。否则,只需
window.open(/* URL of the Ajax request */); -
效果很好!现在我只需要弄清楚如何自动设置文件名。
-
感谢@PeeyushKushwaha 提供链接。在常规的 javascript 中,我认为这很好用。但是,我在 React JS 环境中工作,将 javascript DOM 从用户那里抽象出来。虚拟 DOM 的概念对我来说仍然很陌生,并且使许多任务变得复杂。
标签: javascript jquery ajax reactjs react-jsx