【问题标题】:How to save CSV file from API response using React?如何使用 React 从 API 响应中保存 CSV 文件?
【发布时间】:2021-01-12 13:01:00
【问题描述】:

在我的应用程序中,我需要在我的计算机上保存一个来自 API 响应的 CSV 文件。发送 POST 请求的函数是(我使用的是 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);
  })
} 

API 的响应是:

我在单击按钮后执行 postCsv 函数。如您所见,响应代码为 200,并且每个数据都已正确发送。我只是不知道我应该怎么做才能下载和保存文件。有人可以帮忙吗?

【问题讨论】:

标签: javascript reactjs csv


【解决方案1】:

正如@coccothis thread 中所建议的,您可以使用download 属性动态生成锚点。

注意:为简单起见,我将演示使用useEffect 和假HttpClient 服务从API 获取数据部分,该服务具有静态get 方法返回数据。但希望您能大致了解。

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>
  );
}

这是一个 Working Sample Code Example 供您参考。

【讨论】:

    【解决方案2】:
    const downloadFile = () => {
          const url = window.URL.createObjectURL(new Blob([response.data])) 
          const link = document.createElement('a')
          link.href = url
          link.setAttribute('download', yourfilename.csv)
          document.body.appendChild(link)
          link.click()
      }
    

    【讨论】:

    • 我不知道为什么这个答案没有投票,它对我来说很好。谢谢@HogasAndreiMarius
    猜你喜欢
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    • 1970-01-01
    • 2022-11-03
    相关资源
    最近更新 更多