0

I have a nodeJS API configured which connects to another API and retrieves a data object, which is a Base64 string.

The client that calls the API endpoint needs to download a PDF file that is made from the base64 data.

How should the data be returned to the client so that it can be converted/prompt download from the browser? Should this be done client or server-side?

StuartM
  • 6,743
  • 18
  • 84
  • 160

1 Answers1

1

Base64 is HTML safe and has utility when you want to create a data URL as a link. This would allow to preload the PDF so that the user instantly gets the file when clicking the link.

However, you just want to download it directly, so just convert it as binary on server side to reduce the network overhead related to base64, and keep the client as light as possible (load less data, use less resources).

Just set the proper content-type in the response (application/pdf if you want the PDF to be opened with the browser's PDF plugin, or application/octet-stream if you want to trigger a regular download) then just create a link to it with a classic <a href=.... You can also do one of the following:

Guerric P
  • 30,447
  • 6
  • 48
  • 86
  • So the NodeJS connects to an old SOAP API. The soap API provides the base64 data object. Are you saying convert that to binary then send the binary as a response to the client? Or something else? – StuartM Mar 21 '20 at 22:26
  • So how should the client handle the binary api response to trigger downloading a pdf file which is just data. That part I am unsure of. Thanks – StuartM Mar 22 '20 at 22:54
  • Thanks, how do I set the content-type on the client side. At the moment the API is returning an object that includes FileName and the Data (binary or base64). – StuartM Mar 24 '20 at 11:21
  • @StuartM you should not return an object, if you want to specify a filename do it in the `Content-Disposition: attachment; filename="filename.pdf"` then put the file as binary directly in the body – Guerric P Mar 24 '20 at 11:31
  • Is this all server side? Sorry I can’t find any info on doing this in JavaScript client side hence the original question – StuartM Mar 24 '20 at 12:52
  • Yes this is server side, do you have control over the server? – Guerric P Mar 24 '20 at 12:53
  • If you dont have control over the server, write `download="filename.pdf"` on the `` link – Guerric P Mar 24 '20 at 12:55