reactjs - 如何从 fetch 请求中的 readableStream 响应中获取可下载文件

标签 reactjs csv download stream rails-api

我有一个 React 应用程序,它向我的 Rails API 发送 POST 请求。我希望我的 API 端点生成一个 csv 文件,然后将该文件发送回 React 应用程序。我希望浏览器为最终用户下载 csv 文件。
这是端点的样子:

  def generate
      // next line builds the csv in tmp directory
      period_recap_csv = period_recap.build_csv
       // next line is supposed to send back the csv as response
      send_file Rails.root.join(period_recap.filepath), filename: period_recap.filename, type: 'text/csv'
    end
在前端,我的请求如下所示:
export function generateCsvRequest(startDate, endDate) {
  fetch("http://localhost:3000/billing/finance-recaps/generate", {
    method: "post",
    headers: {
      Authorisation: `Token token=${authToken}`,
      'Accept': 'text/csv',
      'Content-Type': 'application/json',
      'X-Key-Inflection': 'camel',
    },
    //make sure to serialize your JSON body
    body: JSON.stringify({
      start_date: startDate,
      end_date: endDate
    })
  })
  .then( (response) => {
    console.log('resp', response);
    return response;
  }).then((data) => {
      // what should I do Here with the ReadableStream I get back ??
      console.log(data);
    }).catch(err => console.error(err));
}
作为响应正文,我得到了一个 readableStream :
enter image description here
我现在应该如何使用 ReadableStream 对象在最终用户浏览器上启动该 CSV 文件的下载?

最佳答案

当您使用 fetch API 时,您的响应对象有一堆方法来处理您获得的数据。用得最多的是json() .如果您需要从服务器下载文件,您需要的是 blob() ,其工作方式与 json() 相同.

response.blob().then(blob => download(blob))
有很多 npm 包可以下载文件。 file-saver是其中之一。一种无需依赖即可工作的方法是使用 a标签。类似的东西:
function download(blob, filename) {
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.style.display = 'none';
  a.href = url;
  // the filename you want
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  window.URL.revokeObjectURL(url);
}
无论如何,使用依赖项将涵盖更多边缘情况,并且通常更兼容。我希望这有用
如果您想在另一个选项卡中显示 pdf 而不是下载它,您可以使用 window.open并传递 window.URL.createObjectURL 生成的 URL .
function showInOtherTab(blob) {
  const url = window.URL.createObjectURL(blob);
  window.open(url);
}

关于reactjs - 如何从 fetch 请求中的 readableStream 响应中获取可下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59394040/

相关文章:

javascript - 如何结合使用 connect() 的两种用法?

file - 付款后直接创建带有链接的自定义 Paypal 按钮

asp.net-mvc - 使用 .net MVC View 将 csv 或 excel 文件导入 SQL Server 2005 的最佳方法

Python 下载器

android - 在Android中下载mp3文件问题

javascript - 在mapDispatchToProps中react-router访问history prop

javascript - React 函数导出在导出后不起作用

javascript - 为什么在reactjs中使用JSON.parse会导致跨源错误?

python - Csv Writer - 尝试在每列中写入变量

python - df.to_csv 构造输出