/**
* 获取数据流
*/
import React from 'react';
import { Button } from 'antd';
import 'antd/dist/antd.css';
import request from 'umi-request';
export default () => {
function download() {
request('/get-data-stream', {
method: 'POST',
// 必须加responseType: 'blob',
responseType: 'blob',
}).then(res => {
const blob = new Blob([res]); //注意拿到的是数据流!!
const objectURL = URL.createObjectURL(blob);
let btn = document.createElement('a');
btn.download = '文件.docx'; //文件类型
btn.href = objectURL;
btn.click();
URL.revokeObjectURL(objectURL);
btn = null;
});
}
return (
<>
<Button type="primary" onClick={download}>
下载文件
</Button>
</>
);
};
或者直接地址下载,这个一般是由后端返回的
window.open('https:123//123123.........')
request.interceptors.request.use(async (url, options) => {
if (
options.method === 'post' ||
options.method === 'put' ||
options.method === 'delete' ||
options.method === 'get'
) {
const headers = {
'Content-Type': 'application/json',
Accept: 'application/json',
token:localStorage.getItem("token")
};
return {
url,
options: { ...options, headers },
};
}
});
React与后端交互:数据流获取与文件下载实践
本文介绍了如何使用React组件通过umi-request从后端获取数据流,并演示了如何将接收到的数据转换为可下载的文件。同时,展示了如何配置请求拦截器以处理不同HTTP方法的请求头。
2748

被折叠的 条评论
为什么被折叠?



