0

I have a file in my database stored using GridFS and the mongoDB gives me a chunks and a 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>

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)?

Please guide me. Thanks!

KnowYourElements
  • 392
  • 1
  • 12
  • 1
    return url/id only (GraphQL) for some service (GET) returning file from GridFS - different headers required for graphql response and files – xadm Jan 10 '21 at 15:40
  • What do you mean by that? Like putting the file in some remote file server then make the graphql return the url? – KnowYourElements Jan 10 '21 at 16:47
  • 1
    not, return some id (or full url) to other (not `/graphql`) endpoint (e.g. `/document?id=someId`) returning (for given id, not easy to guess or auth required) content/file directly from GridFS – xadm Jan 10 '21 at 16:56

1 Answers1

0

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')); 

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' />
Dharman
  • 30,962
  • 25
  • 85
  • 135
KnowYourElements
  • 392
  • 1
  • 12