節點幫助

Multer Node.js(開發人員如何使用)

發佈 2024年9月29日
分享:

介紹

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

Multer 是一個 Node.js 中介軟體,可以更容易地處理多部分表單數據(multipart/form-data),該格式主要用於文件上傳。 由於其高度靈活性,開發人員可以指定文件大小限制、儲存選項和文件過濾,以確保安全且有效的文件上傳。 Multer 是開發人員希望輕鬆將文件上傳功能集成到其應用程式中的頂級選擇,因為它很容易與 Express.js 集成。

反之, IronPDF 是一個強大的 PDF 創建庫,使程式設計師能夠使用 HTML 文本生成 PDF 文件。 擁有多種功能,包括支持 JavaScript 執行、CSS 樣式及字體和圖片嵌入,這是將動態網頁信息轉換為專業外觀 PDF 的完美工具。

我們將演示這兩個強大工具之間的順暢合作,具體介紹如何設置和使用 IronPDF 來創建 PDF 文件,以及在 Node.js 應用程式中使用 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

Multer 的 Node.js 功能

檔案儲存選項

  • Multer 能夠將上傳的文件直接存儲到磁碟。 磁碟儲存引擎允許您提供檔案名和目標目錄。 這對於需要將檔案保存以供日後使用的程式特別有用。
  • 記憶體存儲:Multer 能夠將文件臨時存儲為緩衝區對象以供瞬間使用。 這在不需要將文件保留在磁盤上並能立即進行處理的情況下非常有幫助。

檔案大小限制

Multer 讓您設定上傳文件的大小限制,可以協助保障伺服器效能,並透過防止上傳過大文件來有效管理儲存資源。 您可以使用限制選項來完成此操作。

檔案篩選

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

處理多個文件

Multer 可以同時管理多個上傳的文件。 可以設置路由以接受包含文件或文件數組的多個字段。 這對於需要一次上傳多個檔案的表單非常有幫助,例如支持檔案和個人資料圖片。

可自定義的存儲引擎

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

與 Express 輕鬆整合

Multer是為了能夠輕鬆整合Express.js而設計的。 使用 middleware 在 Express 路由中,可以輕鬆地將檔案上傳功能添加到您的網絡應用程式中。

自動處理多部分數據

Multer 透過自動解析 multipart/form-data,簡化了伺服器端程式碼中處理文件上傳的過程,方法是將上傳的文件和表單數據提供在 req 物件上。

單個和多個文件上傳

Multer 提供多種方式 (單一、陣列和欄位) 管理一個或多個檔案的上傳。 單一方法處理每個請求的一個文件,數組方法支援具有相同欄位名稱的多個文件,而欄位方法可以處理具有不同欄位名稱的大量文件。

創建和配置 Multer Node.js JS

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

安裝相依性

安裝 Multer 和 Express 是第一步。可使用 npm

npm install multer
npm install express
npm install multer
npm install express
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npm install multer npm install express
VB   C#

配置 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}`);
});
Private const express = require( 'express');
Private const multer = require( 'multer');
Private const path = require( 'path');
Private const fs = require( 'fs');
' Initialize Express
Private const app = express()
' Set up storage configuration for Multer
Private const storage = multer.diskStorage({ destination:= (req, file, cb) =>
	cb(Nothing, 'uploads/');
'INSTANT VB TODO TASK: Lambda expressions and anonymous methods are not converted by Instant VB if local variables of the outer method are referenced within the anonymous method:
, filename: (req, file, cb) =>
' Configure file filter function to allow only certain file types
'INSTANT VB TODO TASK: Lambda expressions and anonymous methods are not converted by Instant VB if local variables of the outer method are referenced within the anonymous method:
const fileFilter = (req, file, cb) =>
If True Then
'INSTANT VB WARNING: Instant VB cannot determine whether both operands of this division are integer types - if they are then you should use the VB integer division operator:
  const allowedFileTypes = /jpeg jpg png gif/
  const mimetype = allowedFileTypes.test(file.mimetype)
  const extname = allowedFileTypes.test(path.extname(file.originalname).toLowerCase())
  If mimetype AndAlso extname Then
	Return cb(Nothing, True)
  Else
	cb(New [Error]( 'Only images are allowed!'));
  End If
End If
' Initialize Multer with storage, file size limit, and file filter options
const upload = multer({
	storage:= storage,
	limits:= { fileSize:= 1024 * 1024 * 5 },
	fileFilter:= fileFilter
})
' Single file upload route
app.post( '/upload-@single', upload.@single('profilePic'), (req, res) =>
If True Then
	Try
		res.send( 'Single file uploaded successfully');
	Catch e1 As err
		res.status(400).send({ [error]:= err.message })
	End Try
End If
)
' Multiple files upload route
app.post( '/upload-multiple', upload.array('photos', 5), (req, res) =>
If True Then
	Try
		res.send( 'Multiple files uploaded successfully');
	Catch e2 As err
		res.status(400).send({ [error]:= err.message })
	End Try
End If
)
' Error handling middleware
'INSTANT VB TODO TASK: Lambda expressions and anonymous methods are not converted by Instant VB if local variables of the outer method are referenced within the anonymous method:
app.use((err, req, res, [next]) =>
' Start the server
const PORT = process.env.PORT 3000
'INSTANT VB TODO TASK: Lambda expressions and anonymous methods are not converted by Instant VB if local variables of the outer method are referenced within the anonymous method:
app.listen(PORT, () =>
VB   C#

Multer Node.js(開發人員如何使用):圖 2 - 使用 Multer 來上傳文件的 Multer Node.js 應用程式

配置存儲系統

destination:表示上傳的文件將儲存的資料夾。

檔案名稱:在每個上傳的檔案中,根據時間戳記和隨機數產生唯一的檔案名稱,同時維持原始的檔案副檔名。

文件過濾器: 一種用於驗證上傳文件類型的選項。 在此範例中,只允許具有 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 頁面上添加文字或圖片水印。

包含標頭和頁尾: The 頁首和頁尾 PDF 文件允許您包含自訂訊息或頁碼。

安裝 IronPDF

使用 node 軟體包管理器安裝所需的 Node.js 軟體包,以啟用 IronPDF 功能。

npm install @ironsoftware/ironpdf
npm install @ironsoftware/ironpdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npm install @ironsoftware/ironpdf
VB   C#

將 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.filename;
    const pdfPath = path.join(__dirname, 'uploads', filename);
    res.download(pdfPath);
  });
// 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.filename;
    const pdfPath = path.join(__dirname, 'uploads', filename);
    res.download(pdfPath);
  });
// 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
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: var config=IronPdf.IronPdfGlobalConfig const app = express();
IronPdf.IronPdfGlobalConfig Const app = express()
Dim config As Dim=IronPdf.IronPdfGlobalConfig Const app
' Set up Multer storage configuration
'INSTANT VB TODO TASK: Lambda expressions and anonymous methods are not converted by Instant VB if local variables of the outer method are referenced within the anonymous method:
const storage = multer.diskStorage({ destination:= (req, file, cb) =>
If True Then
	cb(Nothing, 'uploads/');
End If
'INSTANT VB TODO TASK: Lambda expressions and anonymous methods are not converted by Instant VB if local variables of the outer method are referenced within the anonymous method:
, filename: (req, file, cb) =>
const upload = multer({ storage:= storage })
' Single file upload route
app.post( '/upload-@single', upload.@single('file'), async(req, res) =>
If True Then
	Try
		const filePath = path.join(__dirname, 'uploads', req.file.filename);
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: 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> `;
		"500" height="600"> </body> </html> `
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: const htmlContent = ` <html> <head> <title> Uploaded File Content</title> </head> <body> <h1> Uploaded File Content</h1> <img src="${filePath}" alt="image" width="500" height
		"image" width="500" height
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: const htmlContent = ` <html> <head> <title> Uploaded File Content</title> </head> <body> <h1> Uploaded File Content</h1> <img src="${filePath}" alt="image" width
		"${filePath}" alt="image" width
'INSTANT VB TODO TASK: The following line contains an assignment within expression that was not extracted by Instant VB:
'ORIGINAL LINE: const htmlContent = ` <html> <head> <title> Uploaded File Content</title> </head> <body> <h1> Uploaded File Content</h1> <img src="${filePath}" alt
		const htmlContent = ` (Of html) (Of head) (Of title) Uploaded File Content</title> </head> (Of body) (Of h1) Uploaded File Content</h1> <img src="${filePath}" alt
		const pdf = Await document.fromHtml(htmlContent)
		const pdfPath = path.join(__dirname, 'uploads', `${@Date.now()}-output.pdf`);
		Await pdf.saveAs(pdfPath)
'INSTANT VB TODO TASK: The following line contains an assignment within expression that was not extracted by Instant VB:
'ORIGINAL LINE: res.send(`File uploaded and PDF generated successfully! <a href="/download-pdf?path=${pdfPath}"> Download PDF</a>`);
		res.send(`File uploaded [and] PDF generated successfully!<a href="/download-pdf?path=${pdfPath}"> Download PDF</a>`)
	Catch e1 As err
		res.status(500).send({ [error]:= err.message })
	End Try
End If
)
' Route to download generated PDF
  app.get( '/download-pdf', (req, res) =>
  If True Then
	  const filename = req.query.filename
	  const pdfPath = path.join(__dirname, 'uploads', filename);
	  res.download(pdfPath)
  End If
  )
' Start the server
const PORT = process.env.PORT 3000
'INSTANT VB TODO TASK: Lambda expressions and anonymous methods are not converted by Instant VB if local variables of the outer method are referenced within the anonymous method:
app.listen(PORT, () =>
VB   C#

我們在提供的 Node.js 代碼中集成了 Multer 和 IronPDF,以構建一個可靠的系統來管理文件上傳和生成 PDF 文件。 我們使用磁碟儲存配置設定 Multer,以使用 Express 框架處理 multipart/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

結論

總之,透過整合提供了一個完整的解決方案,以組織用戶生成的內容並將其轉化為精美的文件。 Multer 檔案上傳使用 IronPDF 在 Node.js 應用程式中用於生成 PDF。 借助大小限制、文件過濾和文件存儲配置等功能,Multer使文件上傳管理變得更容易。 另一方面,IronPDF 提供自訂選項並支援各種樣式元素,使其能夠 轉換 HTML 資訊 成為高品質的 PDF 文件。

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

透過整合提供功能豐富的高級軟體解決方案給客戶和最終用戶變得更加容易。 IronPDFIronSoftware 技術整合到您的企業應用程式開發堆疊中。 此外,這一強大的基礎將促進項目、後端系統和流程改進。

IronPDF.

了解更多其他 IronSoftware. 由於它們豐富的 文檔, 充滿活力的線上開發者社群,以及頻繁的修訂,這些技術是當代軟體開發項目的理想選擇。

< 上一頁
Node.js Fetch(開發者如何使用)
下一個 >
uuid NPM (對開發者而言如何運作)

準備開始了嗎? 版本: 2024.9 剛剛發布

免費 npm 安裝 查看許可證 >