How to load a pdf file stored on the server from the client side in the node.js server

How to allow a client to download a PDF file stored on a server using node.js.

Please help me with this code.

fs.readFile('temp/xml/user/username.pdf',function(error,data){ if(error){ res.json({'status':'error',msg:err}); }else{ res.json({'status':'ok',msg:err,data:data}); } }); 
+4
source share
2 answers

Express has 2 convenience methods for sending files. The difference is as follows:

+8
source

Send the correct mime type , and then the contents of the pdf.

 fs.readFile('temp/xml/user/username.pdf',function(error,data){ if(error){ res.json({'status':'error',msg:err}); }else{ res.writeHead(200, {"Content-Type": "application/pdf"}); res.write(data); res.end(); } }); 

I assume res is your response object.


Ah, but you are using Express. Use Jonathan's answer instead.

+5
source

Source: https://habr.com/ru/post/1498519/


All Articles