Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to download a pdf file stored in a server in client side in node.js server

How to allow a client to download a pdf file stored in a server using node.js.

Please, someone help me out 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});
    }
});
like image 616
sridhar Avatar asked Aug 23 '13 01:08

sridhar


2 Answers

Express has 2 convenience methods available for sending files. The difference being:

  • Simply sending the file:

    res.sendfile('temp/xml/user/username.pdf');
    
  • Or with Content-Disposition to suggest saving to disk:

    res.download('temp/sml/user/username.pdf');
    
like image 175
Jonathan Lonowski Avatar answered Oct 03 '22 15:10

Jonathan Lonowski


Send the correct mime-type, and then the content 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'm assuming res is your response object.


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

like image 31
chris-l Avatar answered Oct 03 '22 15:10

chris-l