如何使用axios下载文件 [英] How to download files using axios
问题描述
我正在使用axios来处理诸如GET和POST之类的基本http请求,并且效果很好.现在,我还需要能够下载Excel文件. axios可以做到这一点吗?如果是这样,那么有人有一些示例代码吗?如果没有,我还能在React应用程序中使用什么来做同样的事情?
I am using axios for basic http requests like GET and POST, and it works well. Now I need to be able to download Excel files too. Is this possible with axios? If so does anyone have some sample code? If not, what else can I use in a React application to do the same?
推荐答案
当响应包含可下载的文件时,响应标头将类似于
When response comes with a downloadable file, response headers will be something like
Content-Disposition: "attachment;filename=report.xls"
Content-Type: "application/octet-stream" // or Content-type: "application/vnd.ms-excel"
您可以做的是创建一个单独的组件,其中将包含一个隐藏的iframe.
What you can do is create a separate component, which will contain a hidden iframe.
import * as React from 'react';
var MyIframe = React.createClass({
render: function() {
return (
<div style={{display: 'none'}}>
<iframe src={this.props.iframeSrc} />
</div>
);
}
});
现在,您可以将可下载文件的URL作为prop传递给此组件,因此,当此组件收到prop时,它将重新呈现并下载文件.
Now, you can pass the url of the downloadable file as prop to this component, So when this component will receive prop, it will re-render and file will be downloaded.
编辑:您还可以使用 js-file-download 模块. 链接到Github存储库
You can also use js-file-download module. Link to Github repo
const FileDownload = require('js-file-download');
Axios.get(`http://localhost/downloadFile`)
.then((response) => {
FileDownload(response.data, 'report.csv');
});
希望这会有所帮助:)
这篇关于如何使用axios下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!