Return file from GraphQL resolve
22,004
Solution 1
GraphQL uses JSON format, which represents as text format, not as binary.
If you don't want download files with REST, then you should:
- Encode your file content into base64 string in the back end. Related question
- Send this string as part of query response.
- Save encoded base64 string as a file in the front end. Related question
But right architecture design is add a file link in the GraphQL response and use browser for downloading/rendering the file.
Solution 2
It's better to send a hashed & temporary link to download it
- Save the file and hash the name on your static server (to limit access to other users)
- The file should be temporary and should expire in a short time
- Send the link of the file in response to API
Related videos on Youtube
Author by
Edd Chang
Updated on July 09, 2022Comments
-
Edd Chang almost 2 years
I am currently working on an application with the current tech stack:
Backend:
Mongoose
Express
Apollo
GraphQL
Frontend:
Vuejs
Apollo
GraphQL
I have succeeded in uploading files to the server using GraphQL, what I am stuck with is how to implement the 'download' feature. With a normal RESTApi endpoint I can use res.download(filePath) and it works. How do I do this with GraphQL since I don't want to use REST.
Or is there any other standard to go by in this scenario?
Thanks!
-
Edd Chang over 2 yearsSo what you mean to say is, that everytime a user requests a file, the server saves it locally and hashes it while generating a temporary link the user can then use to download it if need be. This link survives for, lets say, a few hours and many users can download it if they have access to it, and after it expires, a new one is generated whenever a new user requests for it again?