javascript - How to save CSV file from API response using React?
问题描述
In my application I need to save on my computer a CSV file which comes from an API response. The function which sends POST request is (I am using Redux):
export const postCsv = sensorData => (dispatch, getState) => {
const token = getState().auth.token;
// Headers
const config = {
headers: {
'Content-Type': "application/json"
}
}
// If token exists, add to headers config
if (token) {
config.headers['Authorization'] = `Token ${token}`
}
// Post request to API
axios.post(`${baseURL}/sensors_data/csv`, sensorData, config)
.then(res => {
console.log(res);
if (res.status === 200) {
dispatch({
type: POST_CSV,
payload: res.data
})
}
})
.catch(err => {
console.log(err.response);
})
}
and response from API is:
I execute the postCsv function after a button click. As you can see, the response code is 200 and every data has been sent correctly. I just don't know what should I do to download and save the file. Can anyone help?
解决方案
As suggested by @cocco in this thread, you could dynamically generate an anchor with the download
attribute.
NOTE: For the sake of simplicity, I'll demo getting the data part form an API using a useEffect
and a fake HttpClient
service that has a static get
method that returns the data. But hope you get the general idea.
import React, { useState, useEffect } from "react";
import HttpClient from "./HttpClient";
import "./style.css";
export default function App() {
const [dataInCSV, setDataInCSV] = useState("");
useEffect(() => {
HttpClient.get().then(res => setDataInCSV(res));
}, []);
return (
<div>
{dataInCSV && (
<a
href={`data:text/csv;charset=utf-8,${escape(dataInCSV)}`}
download="filename.csv"
>
download
</a>
)}
</div>
);
}
Here's a Working Sample Code Example for your ref.
推荐阅读
- c++ - 尝试使用一个类,但没有打印任何内容。不会产生错误。我错过了什么吗?
- computation-theory - 带有抽引理的语言的规律性
- vb.net - 如何在 Word 互操作中指定枚举值?
- function - Haskell 中的折叠实现
- c# - 如何从 C# 类导入数据
- arrays - 使用数组作为属性访问结构时出错
- android - Qt for Android 在屏幕方向更改后 1 秒后发送 MouseReleaseEvent 而不释放屏幕
- binary - 展平二叉树以列出(有序)
- node.js - 如何从使用 axios 的 API 调用中获取的值设置 FulsionText?
- java - 如何改进我的 java 代码以减少 android studio 上的内存垃圾?