6

All the PDF files are saved in the filesystem on the server, how to make the files to be downloadable in client side.

for Ex :

 app.use('/pdfDownload', function(req, res){
  var pathToTheFile = req.body.fileName;
   readFile(pathToTheFile, function(data){
      //code to make the data to be downloadable;
    });
 });

is the request made

function readFile(pathToTheFile, cb){
   var fs = require('fs');
   fs.readFile(pathToTheFile, function(err, data){
      //how to make the file fetched to be downloadable in the client requested
      //cb(data);
   }); 
}

1 Answer 1

9

You can use express.static, set it up early in your app:

app.use('/pdf', express.static(__dirname + '/pathToPDF'));

And it will automatically do the job for you when browser navigates to e.g. '/pdf/fooBar.pdf'.

Sign up to request clarification or add additional context in comments.

7 Comments

@Makisms but what about the 'pathToTheFile' it'll be retrieved using the req object
Static will resolve it automatically. So if you go to /pdf/test.pdf then it will try to find file /pathToPDF/test.pdf.
sorry bro i couldn't get you, If all the files are in /tmp/files/pdf directory. And the filename in the req is like ObjectId.pdf how will it flow ? could you please explain thanks
I understood you're comment, i think i'm doing a wrong request from clien side $.get('/pathToPDF/fileName.pdf', function(data){ }); is it correct ?
You want to open PDF as new tab? Or what you want to get on client side? As well if all files are in /tmp/files/pdf, then you need to do: app.use('/pdf', express.static('/tmp/files/pdf'));. Express will resolve the end of url and will get the right file. Just set up express, and then try to navigate in browser to pdf file.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.