reactjs - 如何在 React js 中下载一种流文件?
问题描述
我想在我的项目中下载一个流文件。实际上,API 的响应形式就像一个 blob。我在这里留下我的代码;
id
并filterBody
作为我的组件的道具到达。
如果有些地方有错误或没有,我真的很困惑吗?谁能帮我找出我的错误?谢谢你。
const fetchBlobFile = async (setBlobFile, id, filterBody) => {
try {
let response = await get(`http://localhost:4000/error/table/export?error_id=${id}`, filterBody)
setBlobFile(response?.data?.blob())
} catch (error) {
}
}
function exportXslFile ({id, filterBody}) {
const [blobFile, setBlobFile] = useState(null)
useEffect(() => {
fetchBlobFile(setBlobFile, id, filterBody)
}, [id])
const export = () => {
const url = window.URL.createObjectURL(blobFile);
window.location = url
}
return (
<button className="export" onClick={export}><ExportXslFile /> Export</button>
)
}
解决方案
我解决了以下问题。此代码完全有效;但只注意导入必要的包。
const fetchBlobFile = async (setBlobFileLoading, id, body) => {
try {
const a = document.createElement("a");
a.style.display = "none";
document.body.appendChild(a);
setBlobFileLoading(true);
var data = JSON.stringify(body);
var config = {
method: 'post',
url: `http://localhost:4000/table/export?errorCsv_id=${id}`,
headers: {
'Content-Type': 'application/json'
},
data: data
};
let response = await axios(config);
setBlobFileLoading(false)
const blobFile = new Blob([response?.data], { type: 'text/csv' });
const url = window.URL.createObjectURL(blobFile);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
} catch (error) {
}
}
function exportXslFile ({id, body}) {
const [blobFileLoading, setBlobFileLoading] = useState(false)
const export = () => {
fetchBlobFile(setBlobFileLoading, id, filterBody)
}
return (
{blobFileLoading && <div className="loading fixed"><Loader /></div>} // set up loader
<button className="export" onClick={export}>Export</button>
) //download button
}
推荐阅读
- laravel - 查询与 slug 而不是 id 的 hasMany 关系?
- nginx - 如何配置 nginx 反向代理
- batch-file - 如何运行批处理脚本以获取文本文件中的输出
- r - 如何使用 plotweb 二分中的 ifelse() 语句根据交互值更改交互的颜色?
- jquery - Angular 5 Jquery问题
- python - 合并熊猫df中的特定值
- computer-vision - 对象跟踪上下文中的本地和全局数据关联有什么区别?
- sql-server - 如何将 XML 数据列表存储在表中
- javascript - Angular 和浏览器在加载数据方面的限制
- bash - 如何在bash中写if条件与其他条件