首页 > 解决方案 > 如何使用 NodeJS FTP 上传缓冲区(pdf 缓冲区)?

问题描述

我使用 将 HTML 转换为 pdf html-pdf-node,但我找不到使用 FTP 将此 PDF 存储在我的服务器中的方法。

我的代码:

const html_to_pdf = require('html-pdf-node');

const generatePDF = () => {
   // The test HTML file
   let content = `
      <html>
         <head>
            <title>Test Application</title>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
            <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
         </head>
         <body>
            <div class="container">
               <h2>Just a Test</h2>
            </div>
         </body>
      </html>
   `;
    
    // generating the PDF 
    let options = { 
        format: 'letter',
        margin: {
            right: '40px',
            left: '40px'
        } 
    };
    let file = { content };
    html_to_pdf.generatePdf(file, options).then((pdfBuffer) => {
       console.log(pdfBuffer); // This is the pdfBuffer. It works because if I send this buffer to my email as an attachment, I can open the PDF
       // How can I create and store a test.pdf file inside my server using FTP connection?
    });
}

谢谢

标签: node.jspdfftp

解决方案


使用ftp应该这样做 - https://www.npmjs.com/package/ftp

安装:npm i ftp和使用类似:

const Client = require("ftp");

// snip snip some code here

html_to_pdf.generatePdf(file, options).then((pdfBuffer) => {
  const c = new Client();
  c.on("ready", function () {
    c.put(pdfBuffer, "foo.pdf", function (err) {
      if (err) throw err;
      c.end();
    });
  });

  const secureOptions = {
      host: "localhost",
      port: 21,
      user: "TheGreatPotatoKingOfEurope",
      password: "5uper_5eekrit!"
  };
  c.connect(secureOptions);
});

推荐阅读