跳過到頁腳內容
NODE 說明

Multer Node.js(開發者的使用方法)

在目前的線上開發環境中,管理文件上傳和產生 PDF 文件是許多應用程式的標準要求。 在Node.js環境下,將IronPDFMulter的功能結合起來,可以得到一個強大的解決方案,有效滿足這些需求。

Multer是一個 Node.js 中間件,它使處理 multipart/form-data(主要用於檔案上傳)變得更加容易。 由於其高度的靈活性,開發人員可以指定檔案大小限制、儲存選項和檔案過濾,以確保安全有效的檔案上傳。 Multer是開發者希望輕鬆地將檔案上傳功能整合到其應用程式中的首選方案,因為它與 Express.js 的整合非常簡單。

相反, IronPDF是一個功能強大的 PDF 創建庫,它使程式設計師能夠使用 HTML 文字建立 PDF 文件。 它具備多種功能,包括支援 JavaScript 執行、CSS 樣式、字體和圖像嵌入,是將動態 Web 資訊轉換為專業外觀 PDF 的完美工具。

我們將透過介紹如何在 Node.js 應用程式中設定和使用IronPDF建立 PDF 文件以及使用Multer管理文件上傳,來展示這兩個強大工具之間的順暢協作。

Multer Node.js 是什麼?

Multer是一個 Node.js 中間件,它使處理 multipart/form-data(主要用於檔案上傳)變得更加容易。 它為處理 Web 應用程式中的檔案上傳功能提供了一種可靠的方法,並且可以輕鬆地與 Express.js 介接。 為確保只上傳授權的檔案類型,Multer 允許開發者指定檔案大小限制、設定儲存選項和套用檔案過濾。

它支援磁碟和記憶體存儲,使伺服器在檔案管理方面具有靈活性。 Multer 也非常適合需要一次提交多個文件的表單,因為它能夠一次處理多個上傳的文件。 綜上所述,Multer 簡化了檔案上傳過程,提高了 Node.js 應用程式安全有效地處理使用者上傳內容的能力。

Multer Node.js(開發者使用方法):圖 1 - Multer Node.js

Node.js Multer 的功能

文件儲存選項

  • Multer 能夠將上傳的檔案直接儲存到磁碟。 磁碟儲存引擎允許您提供檔案名稱和目標目錄。 這對於需要保存文件以供將來使用的程序尤其有用。 *記憶體儲存:Multer 能夠將檔案作為緩衝區物件儲存在記憶體中以供暫時使用。 這在文件無需保存在磁碟上且可以立即處理的情況下非常有用。

檔案大小限制

Multer 允許您設定上傳檔案的大小限制,這可以透過防止上傳過大的檔案來幫助保護伺服器效能和有效管理儲存資源。 您可以使用限制選項來實現此目的。

文件篩選

Multer 有一個檔案過濾器選項,可以讓你管理哪些檔案可以被接受。 此功能可以拒絕不符合要求的文件,還可以驗證文件的 MIME 類型和其他屬性。 這樣就保證了只有特定類型的文件(如論文和圖像)才能提交。

處理多個文件

Multer 可以管理同時上傳的多個檔案。 可以設定路由以接受包含文件或文件數組的多個欄位。 這對於用戶需要一次上傳多個文件(例如證明文件和個人資料圖片)的表單非常有用。

可客製化儲存引擎

除了內建的磁碟和記憶體儲存解決方案之外,Multer 還允許您設計新的儲存引擎。 為了獲得最佳靈活性,您可以建立自己的文件上傳管理邏輯,包括文件的保存位置和保存方式。

輕鬆與 Express 集成

Multer 的設計旨在輕鬆與 Express.js 整合。 透過在 Express 路由中使用中間件,可以輕鬆為您的 Web 應用程式新增檔案上傳功能。

自動處理多部分數據

Multer 透過自動解析 multipart/form-data,簡化了伺服器端程式碼中處理檔案上傳的過程,使上傳的檔案和表單資料可在 req 物件上使用。

單一文件和多文件上傳

Multer 提供了多種方式(單一檔案、陣列和欄位)來管理一個或多個檔案的上傳。 single 方法每次要求處理一個文件,array 方法支援多個具有相同欄位名稱的文件,fields 方法可以處理多個具有不同欄位名稱的文件。

建立和配置 Multer Node.js JS

以下步驟可用於在Node.js應用程式中建置和設定Multer

安裝依賴項

安裝 Multer 和 Express 是第一步。可以使用npm來完成此操作:

npm install multer
npm install express
npm install multer
npm install express
SHELL

配置 Multer

在您的.js檔案中配置 Multer 以處理檔案上傳。以下是詳細圖示:

const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// Initialize Express
const app = express();

// Set up storage configuration for Multer
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/'); // Directory to save uploaded files
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname)); // Unique filename
  }
});

// Configure file filter function to allow only certain file types
const fileFilter = (req, file, cb) => {
  const allowedFileTypes = /jpeg|jpg|png|gif/;
  const mimetype = allowedFileTypes.test(file.mimetype);
  const extname = allowedFileTypes.test(path.extname(file.originalname).toLowerCase());
  if (mimetype && extname) {
    return cb(null, true);
  } else {
    cb(new Error('Only images are allowed!'));
  }
};

// Initialize Multer with storage, file size limit, and file filter options
const upload = multer({
  storage: storage,
  limits: { fileSize: 1024 * 1024 * 5 }, // 5 MB file size limit
  fileFilter: fileFilter
});

// Single file upload route
app.post('/upload-single', upload.single('profilePic'), (req, res) => {
  try {
    res.send('Single file uploaded successfully');
  } catch (err) {
    res.status(400).send({ error: err.message });
  }
});

// Multiple files upload route
app.post('/upload-multiple', upload.array('photos', 5), (req, res) => {
  try {
    res.send('Multiple files uploaded successfully');
  } catch (err) {
    res.status(400).send({ error: err.message });
  }
});

// Error handling middleware
app.use((err, req, res, next) => {
  if (err) {
    res.status(400).send({ error: err.message });
  }
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// Initialize Express
const app = express();

// Set up storage configuration for Multer
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/'); // Directory to save uploaded files
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname)); // Unique filename
  }
});

// Configure file filter function to allow only certain file types
const fileFilter = (req, file, cb) => {
  const allowedFileTypes = /jpeg|jpg|png|gif/;
  const mimetype = allowedFileTypes.test(file.mimetype);
  const extname = allowedFileTypes.test(path.extname(file.originalname).toLowerCase());
  if (mimetype && extname) {
    return cb(null, true);
  } else {
    cb(new Error('Only images are allowed!'));
  }
};

// Initialize Multer with storage, file size limit, and file filter options
const upload = multer({
  storage: storage,
  limits: { fileSize: 1024 * 1024 * 5 }, // 5 MB file size limit
  fileFilter: fileFilter
});

// Single file upload route
app.post('/upload-single', upload.single('profilePic'), (req, res) => {
  try {
    res.send('Single file uploaded successfully');
  } catch (err) {
    res.status(400).send({ error: err.message });
  }
});

// Multiple files upload route
app.post('/upload-multiple', upload.array('photos', 5), (req, res) => {
  try {
    res.send('Multiple files uploaded successfully');
  } catch (err) {
    res.status(400).send({ error: err.message });
  }
});

// Error handling middleware
app.use((err, req, res, next) => {
  if (err) {
    res.status(400).send({ error: err.message });
  }
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
JAVASCRIPT

Multer Node.js(開發者使用方法):圖 2 - 使用 Multer 上傳檔案的 MulterNode.js 應用程式

配置儲存系統

-目標位置:指示上傳的檔案將儲存在哪個資料夾中。

  • filename :保留原始檔案副檔名,同時根據時間戳記和隨機數為每個上傳的檔案建立唯一的檔案名稱。 -檔案篩選器:用於驗證上傳檔案的檔案類型的選項。 本範例中僅允許使用副檔名為 jpeg、jpg、png 或 gif 的圖片檔案。

初始化 Multer:

-儲存:描述儲存的設定。

  • limits :定義允許的最大檔案大小(本例為 5 MB)。
  • fileFilter :使用檔案過濾器功能。

開始使用 IronPdf

當使用IronPDF生成 PDF 文檔,並使用Multer處理文件上傳時,就創建了一個強大的解決方案,用於管理用戶生成的內容並將其轉換為精美的 PDF。 以下將介紹如何在Node.js應用程式中安裝和組合這兩個函式庫。

什麼是 IronPDF?

IronPDF是一套應用程式庫,旨在簡化 PDF 文件的建立、編輯和管理。 借助此應用程序,開發人員可以從 HTML 文件中提取文字和圖像,添加標題和浮水印,合併多個 PDF 頁面,以及執行各種其他操作。 IronPDF 全面的文件和使用者友好的 API 使開發人員能夠輕鬆地自動產生高品質的 PDF 文件。 IronPDF 包含了改善文件工作流程所需的所有功能和功能,並在各種場景(例如建立文件、報告和發票)中提供一流的使用者體驗。

Multer Node.js(開發者使用方法):圖 3 - IronPDF for Node.js:Node.js PDF 函式庫

IronPDF 的特點

處理任何類型的 HTML 文字(包括 CSS 和 JavaScript)的一種快速簡便的方法是將其轉換為 PDF。

PDF 文件合併:為了簡化文件管理工作,可以將多個 PDF 文件合併為一個 PDF 文件。

文字和圖像提取:從 PDF 文件中提取文字和圖像,以便用於進一步的資料處理或分析。

浮水印:出於安全或品牌推廣的原因,您可以為 PDF 頁面添加文字或圖片浮水印。

新增頁首和頁尾:PDF 文件的頁首和頁尾可讓您新增自訂訊息或頁碼。

安裝 IronPDF

使用 Node 套件管理器安裝所需的 Node.js 套件,以啟用 IronPDF 功能。

npm install @ironsoftware/ironpdf
npm install @ironsoftware/ironpdf
SHELL

將 Multer Node.js 與 IronPDF 集成

修改app.js ,設定IronPDF來建立 PDF 文件,並設定 Multer來處理文件上傳。

const express = require('express');
const multer = require('multer');
const path = require('path');
const IronPdf = require('@ironsoftware/ironpdf');
const document = IronPdf.PdfDocument;
var config = IronPdf.IronPdfGlobalConfig;

// Initialize Express
const app = express();

// Set up Multer storage configuration
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/'); // Directory to save uploaded files
  },
  filename: (req, file, cb) => {
    cb(null, `${Date.now()}-${file.originalname}`); // Unique filename
  }
});

const upload = multer({ storage: storage });

// Single file upload route
app.post('/upload-single', upload.single('file'), async (req, res) => {
  try {
    // Read the uploaded file
    const filePath = path.join(__dirname, 'uploads', req.file.filename);

    // Create HTML content for PDF
    const htmlContent = `
      <html>
        <head>
          <title>Uploaded File Content</title>
        </head>
        <body>
          <h1>Uploaded File Content</h1>
          <img src="${filePath}" alt="image" width="500" height="600">
        </body>
      </html>
    `;

    // Initialize IronPDF
    const pdf = await document.fromHtml(htmlContent);

    // Save PDF to file
    const pdfPath = path.join(__dirname, 'uploads', `${Date.now()}-output.pdf`);
    await pdf.saveAs(pdfPath);

    // Respond to the client
    res.send(`File uploaded and PDF generated successfully! <a href="/download-pdf?path=${pdfPath}">Download PDF</a>`);
  } catch (err) {
    res.status(500).send({ error: err.message });
  }
});

// Route to download generated PDF
app.get('/download-pdf', (req, res) => {
  const filename = req.query.path;
  res.download(filename);
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
const express = require('express');
const multer = require('multer');
const path = require('path');
const IronPdf = require('@ironsoftware/ironpdf');
const document = IronPdf.PdfDocument;
var config = IronPdf.IronPdfGlobalConfig;

// Initialize Express
const app = express();

// Set up Multer storage configuration
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/'); // Directory to save uploaded files
  },
  filename: (req, file, cb) => {
    cb(null, `${Date.now()}-${file.originalname}`); // Unique filename
  }
});

const upload = multer({ storage: storage });

// Single file upload route
app.post('/upload-single', upload.single('file'), async (req, res) => {
  try {
    // Read the uploaded file
    const filePath = path.join(__dirname, 'uploads', req.file.filename);

    // Create HTML content for PDF
    const htmlContent = `
      <html>
        <head>
          <title>Uploaded File Content</title>
        </head>
        <body>
          <h1>Uploaded File Content</h1>
          <img src="${filePath}" alt="image" width="500" height="600">
        </body>
      </html>
    `;

    // Initialize IronPDF
    const pdf = await document.fromHtml(htmlContent);

    // Save PDF to file
    const pdfPath = path.join(__dirname, 'uploads', `${Date.now()}-output.pdf`);
    await pdf.saveAs(pdfPath);

    // Respond to the client
    res.send(`File uploaded and PDF generated successfully! <a href="/download-pdf?path=${pdfPath}">Download PDF</a>`);
  } catch (err) {
    res.status(500).send({ error: err.message });
  }
});

// Route to download generated PDF
app.get('/download-pdf', (req, res) => {
  const filename = req.query.path;
  res.download(filename);
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
JAVASCRIPT

我們將 Multer 和 IronPDF 整合到提供的 Node.js 程式碼中,以建立一個可靠的系統來管理文件上傳和產生 PDF 文件。 我們使用磁碟儲存配置 Multer 來處理使用 Express 框架的多部分/表單資料檔案上傳,為每個上傳的檔案賦予唯一的檔案名稱和目標目錄。 Multer 保存使用者透過/upload-single路由上傳的文件,伺服器檢查這些文件的內容。

Multer Node.js(開發者使用方法):圖 4 - 使用 Multer 上傳文件,然後將上傳的文件(.jpg 圖片)加入 HTML 內容中,並使用 IronPDF 將其轉換為 PDF。

之後,將此內容整合到一個基本的HTML範本中。 這段 HTML 程式碼會被輸入到 IronPDF 中,IronPDF 會建立一個 PDF 檔案並將其儲存在 uploads 目錄中。 最後,伺服器會提供一個鏈接,供用戶下載生成的 PDF 文件。 此整合展示了Multer處理文件上傳的效率, IronPDF將這些上傳的文件轉換為高品質的 PDF,從而在 Node.js 應用程式中提供流暢的文件管理和文件創建功能。

Multer Node.js(開發者使用方法):圖 5 - 使用 IronPDF 產生的輸出 PDF

結論

總而言之,透過在 Node.js 應用程式中整合Multer (用於文件上傳)和IronPDF (用於 PDF 生成),提供了一個完整的解決方案,用於組織用戶生成的內容並將其轉化為精美的論文。 Multer具備大小限制、檔案過濾和檔案儲存設定等功能,讓檔案上傳管理更輕鬆。 另一方面, IronPDF提供自訂選項和對各種樣式元素的支持,可以將 HTML 資訊轉換為高品質的 PDF 文件。

這兩個庫可以結合起來創建靈活的應用程序,使用戶能夠提交文件並自動將其轉換為美觀的 PDF 文件。 此整合提高了文件產生操作的效率,並透過簡化發票、證書、報告等的生成流程,改善了使用者體驗。

透過將IronPDF整合到企業應用程式開發堆疊中,為客戶和最終用戶提供功能豐富的優質軟體解決方案變得更加容易。 此外,這項堅實的基礎將有助於專案、後端系統和流程的改進。

IronPDF.

了解更多Iron Software的其他產品。 由於這些技術擁有豐富的文件、活躍的線上開發者社群以及頻繁的更新,因此它們是現代軟體開發專案的絕佳選擇。

Darrius Serrant
全棧軟件工程師 (WebOps)

Darrius Serrant 擁有邁阿密大學計算機科學學士學位,目前任職於 Iron Software 的全栈 WebOps 市場營銷工程師。從小就迷上編碼,他認為計算既神秘又可接近,是創意和解決問題的完美媒介。

在 Iron Software,Darrius 喜歡創造新事物,並簡化複雜概念以便於理解。作為我們的駐場開發者之一,他也自願教學生,分享他的專業知識給下一代。

對 Darrius 來說,工作令人滿意因為它被重視且有實際影響。