【问题标题】:How to download a file stored using GridFS and returned using GraphQL in the React/Javascript Client?如何下载使用 GridFS 存储并在 React/Javascript 客户端中使用 GraphQL 返回的文件?
【发布时间】:2021-04-15 14:18:24
【问题描述】:

我的数据库中有一个使用 GridFS 存储的文件,mongoDB 给了我一个chunks 和一个files

chunks

_id: <int>
files_id: <int>
n: 0,
data: Binary(<string>, 0)

files

_id: <id>
length: <int>
chunkSize: <int>
uploadDate: <date>
filename: <string>
md5: <string>

有没有办法通过 GraphQL 在客户端下载这个文件?例如返回一个块并在前端将其转换为客户端下载?或者也许一种方法直接将文件发送到graphql并让客户端下载它(到目前为止一切都表明这是不可能的)?

请指导我。谢谢!

【问题讨论】:

  • 仅返回 url/id (GraphQL) 用于从 GridFS 返回文件的某些服务 (GET) - graphql 响应和文件需要不同的标头
  • 你这是什么意思?就像将文件放在某个远程文件服务器中然后让graphql返回url?
  • 不是,将一些 id(或完整的 url)返回到其他(不是/graphql)端点(例如/document?id=someId)返回(对于给定的 id,不容易猜测或需要身份验证)内容/文件直接来自 GridFS

标签: mongodb graphql gridfs


【解决方案1】:

我所做的只是将文件转换为 base64 字符串 (related question)。然后在解析器中返回字符串。

const file_buffer = fs.readFileSync(filepath);
const contents_in_base64 = file_buffer.toString('base64');
return contents_in_base64;

或者,如果您无权访问与原始问题相同的文件,那么您可以

chunk.data.toString('base64')); 

然后在前端,我只是将base64放在一个锚标签上(related question)。

<a download={`${filename}.pdf`} href={`data:application/pdf;base64,${base64pdf}`} title='Download pdf document' />

【讨论】:

  • 适合小文件
猜你喜欢
  • 2017-04-14
  • 2013-09-22
  • 1970-01-01
  • 2016-01-07
  • 2011-04-30
  • 1970-01-01
  • 2023-03-19
  • 2020-12-15
  • 1970-01-01
相关资源
最近更新 更多