如何在React/Javascript客户端中下载使用GridFS存储并使用GraphQL返回的文件? [英] How to download a file stored using GridFS and returned using GraphQL in the React/Javascript Client?

查看:56
本文介绍了如何在React/Javascript客户端中下载使用GridFS存储并使用GraphQL返回的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据库中使用GridFS存储了一个文件,mongoDB给了我文件.

I have a file in my database stored using GridFS and the mongoDB gives me a chunks and a files.

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

文件

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

是否可以通过GraphQL在客户端中下载此文件?例如,例如返回一个块并在前端将其转换以供客户端下载?或者也许是一种直接将文件发送到graphql并让客户端下载文件的方式(到目前为止,所有内容都指出这是不可能的)?

Is there a way to download this file in the client through GraphQL? Like for example returning a chunk and converting it in the frontend side for the client to download? Or maybe a way send a file directly to graphql and make the client download it (so far everything points that it's not possible)?

请指导我.谢谢!

推荐答案

我所做的只是将文件转换为base64字符串(相关问题).然后在解析器中返回字符串.

What I did was just I converted the file into a base64 string (related question). Then return the string in the resolver.

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

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

Alternatively, if you don't have access to the file same as the original question then you can

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

然后在前端,我将base64放在锚标记上(相关问题).

Then on the front-end, I just put the base64 on an anchor tag (related question).

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

这篇关于如何在React/Javascript客户端中下载使用GridFS存储并使用GraphQL返回的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆