【问题标题】:Download file in react client from flask remote server从烧瓶远程服务器下载反应客户端中的文件
【发布时间】:2019-01-01 17:54:15
【问题描述】:

我有一个从我的 React 客户端到我的远程 Flask 服务器的 post fetch 请求,如下所示:

fetch(FETCH_URL, {
  method: 'POST',
  body: data,
  headers: {
    'Content-Type': 'application/json'
  }
}).then((response) => {
    var a = response.body.getReader();
    a.read().then(({ done, value }) => {
        console.log(new TextDecoder("utf-8").decode(value));
      }
    );
});

response.body 以 ReadableStream 对象的形式出现,因此我能够提取一个 Uint8array,然后将其解码为我从烧瓶服务器发回的 txt 文件的内容,如上面的代码所示。

此时我迷路了,我想做的是向我的远程服务器发送一个带有文件名的请求(在请求的数据中),然后将该文件下载到我的计算机上。

如上所示,我尝试向远程服务器发送 fetch 请求,然后在 flask 中,我的服务器找到并打开存储在服务器本身上的文件,并将文件发回。

filename = request.get_json()['filename']
f = open(filename)
return f

现在的问题是,根据我所阅读的内容,我无法仅通过 react 在我的计算机上创建文件。即便如此,我不知道这是否适用于所有类型的文件或仅适用于 txt 文件。有没有人有任何指导来实现我从远程烧瓶服务器下载文件的最终目标。

【问题讨论】:

标签: javascript python reactjs flask download


【解决方案1】:

如果您的要求是使用从响应中收到的数据创建一个文件。以下解决方案应该可以工作。

  1. 使用收到的文本创建 blob 对象
  2. 为该 blob 创建 Blob 对象 URL
  3. 使用该 URL 触发下载对象

由于这是纯 Javascript 解决方案,它独立于 React 或您使用的任何库。

解决方案:

fetch(FETCH_URL, {
  method: 'POST',
  body: data,
  headers: {
    'Content-Type': 'application/json'
  }
}).then((response) => {
    var a = response.body.getReader();
    a.read().then(({ done, value }) => {
        // console.log(new TextDecoder("utf-8").decode(value));
        saveAsFile(new TextDecoder("utf-8").decode(value), 'filename');
      }
    );
});


function saveAsFile(text, filename) {
  // Step 1: Create the blob object with the text you received
  const type = 'application/text'; // modify or get it from response
  const blob = new BlobBuilder([text], {type});

  // Step 2: Create Blob Object URL for that blob
  const url = URL.createObjectURL(blob);

  // Step 3: Trigger downloading the object using that URL
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  a.click(); // triggering it manually
}

【讨论】:

  • 谢谢,我已接受您的回答作为解决方案。现在我在尝试完成同样的事情时遇到了一个不同的问题,你认为你可以看看吗? stackoverflow.com/questions/51525964/…
【解决方案2】:

您也可以使用<Button href="${YOUR_FILE_URL}"/>下载flask发送的文件。

【讨论】:

    猜你喜欢
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 2019-09-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多