从Flask远程服务器下载React Client中的文件

Ber*_*uez 1 javascript python download flask reactjs

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

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));
      }
    );
});
Run Code Online (Sandbox Code Playgroud)

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

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

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

filename = request.get_json()['filename']
f = open(filename)
return f
Run Code Online (Sandbox Code Playgroud)

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

Kam*_*n J 5

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

  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
}
Run Code Online (Sandbox Code Playgroud)