跳過到頁腳內容
NODE 說明

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

在當前的線上開發環境中,管理檔案上傳和生成PDF文件是許多應用程式的基本需求。 總結IronPDFMulter在Node.js環境中的功能,提供了一個強大的解決方案來有效地處理這些需求。

Multer是一個Node.js中介軟體,使處理多部件/form-data(主要用於文件上傳)更容易。 由於其極大的靈活性,開發人員可以指定文件大小限制、存儲選項和文件過濾,以確保安全和有效的文件上傳。 因為Multer易於與Express.js整合,所以對於希望輕鬆整合文件上傳功能到應用程式的開發者來說,Multer是首選。

另一方面,IronPDF是功能強大的PDF創建程式庫,使程式設計師能夠使用HTML文本創建PDF文件。 它擁有許多功能,包括支援JavaScript執行、CSS樣式、字型和圖像嵌入,是將動態網頁信息轉換為專業外觀PDF的理想工具。

我們將示範這兩個強大的工具之間的順暢合作,通過展示如何設置和使用IronPDF創建PDF文件,以及Multer管理Node.js應用程式中的文件上傳。

Multer Node.js是什麼?

Multer是一個Node.js中介軟體,可以更容易地處理多部件/form-data,主要用於文件上傳。 它提供了在Web應用程式中處理文件上傳功能的可靠方法,並能輕鬆與Express.js介面整合。 為了確保只有授權的文件類型被上傳,Multer讓開發人員能夠指定文件大小限制、配置存儲選項並應用文件過濾。

通過支援磁碟和記憶體存儲,Multer為伺服器在管理文件方面提供了靈活性。 Multer還非常適合需要一次提交多個文件的表單,因為它可以同時處理多個文件上傳。 總而言之,Multer簡化了文件上傳過程,提高了Node.js應用程式安全有效地處理用戶上傳內容的能力。

Multer Node.js(對開發者如何運作):圖1 - Multer Node.js

Multer在Node.js上的特點

文件存儲選項

  • Multer能夠將上傳的文件直接存到磁碟中。 磁碟存儲引擎允許您提供文件名和目標目錄。 這對需要將文件保存以供將來使用的程式特別有用。
  • 記憶體存儲:Multer能夠將文件以緩衝物件的形式存儲在記憶體中以供暫時使用。 這在不需要將文件保存在磁碟上並且可以立即處理的情況下很有幫助。

文件大小限制

Multer允許您設定對上傳文件的大小限制,以協助保護伺服器的性能,並有效地管理存儲資源,避免上傳過大的文件。 您可以使用限制選項來達到此目的。

文件過濾

Multer有一個fileFilter選項,讓您管理接受哪些文件。 不符合要求的文件可以被這個功能拒絕,而這個功能還可以檢驗文件的MIME類型及其他屬性。 這保證了只有特定類型的文件,例如文件和圖像,被提交。

處理多個文件

Multer能夠管理同時上傳的多個文件。 可以設置路由以接受包含多個字段的文件或文件的數組。 這對於用戶必須一次提交多個文件的表單(例如支持文檔和個人資料圖像)非常有幫助。

可自定義的存儲引擎

除了內建的磁碟與記憶體存儲解決方案,Multer允許您設計新的存儲引擎。 為了獲得最佳靈活性,您可以建立自己的邏輯來處理文件上傳,包括文件存儲的地點與方式。

輕鬆整合Express

Multer設計為易於與Express.js整合。 作為中介軟體使用在您的Express路由中,可以輕鬆地將文件上傳功能添加到Web應用程式中。

自動處理多部件數據

通過自動解析multipart/form-data,Multer簡化了在服務器端代碼中處理文件上傳的過程,將上傳的文件和表單數據置於req物件中。

單一與多個文件上傳

Multer有多種方法(單一、數組和字段)來處理一個或多個文件的上傳。 單一方法每個請求處理一個文件,數組方法支援擁有相同字段名的多個文件,字段方法可處理具有不同字段名的多個文件。

創建與配置Multer Node.js JS

可以使用以下步驟來構建和設置Multer在Node.js應用程式中運行:

安裝相依

安裝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應用程式

配置存儲系統

  • destination:表示上傳的文件將存儲在哪個文件夾中。
  • filename:在創建每個上傳文件的唯一文件名時保留原始文件擴展名,基於時間戳和隨機數。
  • 文件過濾:一個驗證上傳文件類型的選項。 在這個例子中,只允許擁有jpeg、jpg、png或gif擴展名的圖像文件。

初始化Multer:

  • storage:描述存儲的設置。
  • 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 package manager安裝所需的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

我們在提供的Node.js代碼中整合Multer與IronPDF,以構建一個可靠的系統,用於管理文件上傳和生成PDF文件。 我們使用Express框架配置具有磁碟存儲配置的Multer來處理多部件/form-data文件上傳,給每個上傳的文件提供一個唯一的文件名和目標目錄。 Multer通過/upload-single路由保存用戶上傳的文件,然後伺服器檢查這些文件的內容。

Multer Node.js(對開發者如何運作):圖4 - 使用Multer上傳文件,然後將上傳的文件(.jpg圖像)添加到HTML內容中,並使用IronPDF轉換為PDF

然後,這些內容被整合到一個基本的HTML模板中。 這個HTML被導入IronPDF,用其創建的PDF文件存儲在上傳目錄中。 最終,伺服器提供生成的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 來說,工作令人滿意因為它被重視且有實際影響。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me