Skip to main content
 首页 » 编程设计

javascript之从 Flask 远程服务器下载 React 客户端中的文件

2025年05月04日24dflying

我有一个从我的 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)); 
      } 
    ); 
}); 

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

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

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

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

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

请您参考如下方法:

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

  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 
}