如何在node.js服务器中下载存储在客户端服务器中的pdf文件

时间:2021-02-15 19:39:48

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

如何允许客户端使用node.js下载存储在服务器中的pdf文件

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});
    }
});

2 个解决方案

#1


8  

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

Express有2种便捷方法可用于发送文件。区别在于:

  • Simply sending the file:

    只需发送文件:

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

    或者使用Content-Disposition建议保存到磁盘:

    res.download('temp/sml/user/username.pdf');
    

#2


5  

Send the correct mime-type, and then the content of the pdf.

发送正确的mime-type,然后发送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.

我假设res是你的响应对象。


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

啊,但你正在使用Express。请改用Jonathan的答案。

#1


8  

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

Express有2种便捷方法可用于发送文件。区别在于:

  • Simply sending the file:

    只需发送文件:

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

    或者使用Content-Disposition建议保存到磁盘:

    res.download('temp/sml/user/username.pdf');
    

#2


5  

Send the correct mime-type, and then the content of the pdf.

发送正确的mime-type,然后发送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.

我假设res是你的响应对象。


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

啊,但你正在使用Express。请改用Jonathan的答案。