欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Node js 中的 Multer中間件(文件上傳)

 更新時(shí)間:2025年03月28日 10:16:02   作者:新華  
本文介紹了Node.js中用于處理文件上傳的Multer中間件,詳細(xì)說明了項(xiàng)目設(shè)置、安裝依賴的步驟,以及如何使用Multer上傳單個(gè)和多個(gè)文件,還介紹了DiskStorage引擎、其他配置選項(xiàng)和錯(cuò)誤處理方法,感興趣的朋友跟隨小編一起看看吧

本文介紹了Node.js中用于處理文件上傳的Multer中間件。闡述了使用Multer的先決條件,包括了解HTML表單、安裝Node.js等。詳細(xì)說明了項(xiàng)目設(shè)置、安裝依賴的步驟,以及如何使用Multer上傳單個(gè)和多個(gè)文件,還介紹了DiskStorage引擎、其他配置選項(xiàng)和錯(cuò)誤處理方法

概述

文件上傳和下載已成為我們經(jīng)常執(zhí)行的非常常用的操作。以任何社交媒體應(yīng)用程序?yàn)槔?用戶可以上傳圖像,也可以下載網(wǎng)站上顯示的圖像。因此,對(duì)于開發(fā)人員來說,了解文件處理是如何完成的和客戶端以及這些文件如何存儲(chǔ)在服務(wù)器端變得很重要。

先決條件

  • 了解 HTML 表單或任何表單 API。
  • 必須安裝Node.js。
  • 對(duì) Node.js 和 Express 有很好的理解。
  • 了解請(qǐng)求-響應(yīng)架構(gòu)和中間件。

Multer 簡(jiǎn)介

Node.js中的 Multer 是一個(gè)中間件,用于輕松處理文件上傳完成后使用的多部分/表單數(shù)據(jù)。為了獲得最大的效率,Multer 構(gòu)建在 busboy 之上,busboy 是一個(gè)node.js模塊,用于處理請(qǐng)求中傳入的 HTML 表單數(shù)據(jù)。Multer 在功能上類似于 Node.js 中的 body 解析器(一種快速中間件),但它只支持多部分?jǐn)?shù)據(jù)。

當(dāng)我們?cè)?nbsp;HTML 中創(chuàng)建任何表單時(shí),默認(rèn)情況下,ENCTYPE 屬性的值為 application/x-www-form-urlencoded。ENCTYPE屬性指定在請(qǐng)求中發(fā)送數(shù)據(jù)時(shí)如何對(duì)表單數(shù)據(jù)進(jìn)行編碼。默認(rèn)內(nèi)容類型以鍵值對(duì)的形式對(duì)數(shù)據(jù)進(jìn)行編碼。這種類型的結(jié)構(gòu)不支持文件上傳操作。

multipart/form-data 是一種內(nèi)容類型,它使瀏覽器以多部分消息的格式對(duì)表單數(shù)據(jù)進(jìn)行編碼。其中的每個(gè)部分都由一個(gè)文本輸入和一個(gè)文件輸入組成,用于表示表單中的每個(gè)字段。

Multer 被廣泛使用,因?yàn)樗?jiǎn)單、非常高效,并且還支持多個(gè)文件上傳。Multer 通過向請(qǐng)求對(duì)象添加兩個(gè)對(duì)象來操作請(qǐng)求對(duì)象 - 即 body 對(duì)象和 file/files 對(duì)象。Multer 添加的 body 對(duì)象包含來自 HTML 表單中文本字段的數(shù)據(jù)。文件或文件對(duì)象包含在表單中上傳的文件。它們可以作為 req.body 和 req.file 或 req.files 訪問,其中 req 是請(qǐng)求對(duì)象。

在Multer的幫助下,只能處理多部分?jǐn)?shù)據(jù)(multipart/form-data)。無法處理其他格式。在本文中,您將學(xué)習(xí)如何在Node.js中使用 Multer 來簡(jiǎn)化處理多個(gè)文件上傳的過程。Multer 還提供了許多在文件存儲(chǔ)期間應(yīng)用的選項(xiàng)或設(shè)置。

項(xiàng)目設(shè)置

要了解 Multer,讓我們創(chuàng)建一個(gè)小項(xiàng)目。在這里,我們將創(chuàng)建一個(gè) multipart/form-data 的 HTML表單,并使用它來嘗試 multer 的不同功能。

現(xiàn)在,作為第一步,創(chuàng)建一個(gè)項(xiàng)目目錄并將其命名為 multer-demo。在此項(xiàng)目目錄中,創(chuàng)建一個(gè)文件index.html,我們將在其中制作 HTML 表單。在index.html文件中編寫以下代碼,以創(chuàng)建一個(gè)包含表單的網(wǎng)頁(yè)。

<!DOCTYPE html>
<html lang = "en">
  <head>
    <meta charset = "UTF-8" />
    <meta name = "viewport" content = "width=device-width, initial-scale=1.0" />
    <title> Multer demo </title>
    <style>
      /* A set of css styles that you can change to make the form attractive. Right now basic styling is used.*/
      .myform {
        display: block;
        margin: auto;
      }
      .form-field {
        padding: 10px;
      }
      .form-field > input {
        display: block;
        margin: auto;
      }
      .form-field > label {
        display: block;
        text-align: center;
      }
    </style>
  </head>
  <body>
    <div>
      <!-- Create an HTML form with the value of action as URL of API endpoint, encoding as multipart data and request method as POST-->
      <form
        action = "http://localhost:3000/upload"
        enctype = "multipart/form-data"
        method = "post"
        class = "myform"
      >
        <div class = "form-field">
          <label>FirstName</label>
          <input
            type = "text"
            id = "firstName"
            name = "firstName"
            placeholder = "Enter your firstname"
          />
        </div>
        <div class = "form-field">
          <label>LastName</label>
          <input
            type = "text"
            id = "lastName"
            name = "lastName"
            placeholder = "Enter your lastname"
          />
        </div>
        <div class = "form-field">
          <label>Upload file here</label>
          <input type = "file" id = "myFile" name = "myFile" multiple = "true" />
        </div>
        <div class = "form-field">
          <input type = "submit" />
        </div>
      </form>
    </div>
  </body>
</html>

在上面的代碼中,使用了表單標(biāo)簽,并且 enctype 屬性已設(shè)置為 multipart/form-data。表單具有用于為 firstName 和 lastName 創(chuàng)建文本輸入字段的輸入標(biāo)記,以及用于支持文件上傳的文件輸入。窗體當(dāng)前將 action 屬性設(shè)置為 http://localhost:3000/upload,方法為 POST。我們將在 Node.js 中創(chuàng)建的 API 的 url 在 action 屬性中指定。

現(xiàn)在,要?jiǎng)?chuàng)建一個(gè) API 來處理 post 請(qǐng)求,您必須在系統(tǒng)中安裝 Node.js。要檢查系統(tǒng)中是否安裝了Node.js,請(qǐng)?jiān)诮K端中執(zhí)行以下命令。

$ node -v

如果您的系統(tǒng)中安裝了Node.js,上述命令將給出系統(tǒng)中安裝的Node.js版本,例如 v16.17.1。

如果出現(xiàn)“找不到命令”錯(cuò)誤,則系統(tǒng)中未安裝Node.js。您可以借助節(jié)點(diǎn)網(wǎng)站上提供的安裝程序輕松安裝Node.js。

安裝 Node.js 后,若要設(shè)置Node.js項(xiàng)目,請(qǐng)?jiān)诋?dāng)前目錄中運(yùn)行以下命令。

$ npm init

上述命令將詢問一組問題,如下所示:

This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help init` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (multer-tutorial)
version: (1.0.0)
description: A tutorial about multer
entry point: (index.js) server.js
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to C:\Users\HP\Documents\DivyaGo\middleware-nodejs\multer-tutorial\package.json:
{
  "name": "multer-tutorial",
  "version": "1.0.0",
  "description": "A tutorial about multer",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}
Is this OK? (yes) yes

回答所有問題后,將創(chuàng)建一個(gè)包含有關(guān)應(yīng)用程序的所有信息的package.json文件。

安裝

現(xiàn)在,要?jiǎng)?chuàng)建 API,您將需要一些其他節(jié)點(diǎn)模塊,這些模塊必須使用 Node Package Manager 進(jìn)行安裝。執(zhí)行以下命令安裝 express 和 multer。

$ npm i express multer

成功執(zhí)行上述命令后,package.json會(huì)在依賴項(xiàng)下顯示 express 和 multer 及其對(duì)應(yīng)版本。

使用 Multer 上傳文件

現(xiàn)在,在安裝所需的依賴項(xiàng)后,您可以開始構(gòu)建 API 來學(xué)習(xí) Multer 的使用。 創(chuàng)建一個(gè)文件server.js,并在其中編寫以下代碼,在 express 的幫助下創(chuàng)建一個(gè)服務(wù)器。

// Import express
const express = require("express");
const PORT = process.env.PORT || 3000;
// Create instance of express.
const app = express();
// Include express.json() middleware
app.use(express.json());
// Include express.urlencoded() middleware
app.use(express.urlencoded({ extended: true }));
// Create a GET endpoint for '/' route
app.get("/", (req, res) => {
    res.send("Welcome to API");
});
// Create a POST endpoint for '/upload' route
app.post("/upload", (req, res) => {
    console.log(req.body);
    res.send("Endpoint for file upload.");
});
// Listen on the specified port.
app.listen(PORT, () => {
    console.log(`Server started on port : ${PORT}`);
});

在上面的代碼中,express 是在 require() 函數(shù)的幫助下導(dǎo)入的。使用了 express.json() 和 express.urlencoded() 中間件。express.json() 用于解析具有 JSON 有效負(fù)載的傳入請(qǐng)求對(duì)象。express.urlencoded() 用于解析具有 urlencoded 有效負(fù)載的請(qǐng)求對(duì)象。它們都在正文解析器上運(yùn)行。已在 / 處創(chuàng)建了一個(gè) GET 端點(diǎn),在 /upload 處創(chuàng)建了一個(gè) POST 端點(diǎn)。已指定應(yīng)用程序偵聽端口 3000。

在終端中運(yùn)行節(jié)點(diǎn)server.js時(shí),服務(wù)器將啟動(dòng)。終端中將顯示以下消息:

$ node server.js
Server started on port : 3000

現(xiàn)在,您可以在瀏覽器的幫助下發(fā)送請(qǐng)求。在瀏覽器上打開 http://localhost:3000。它將顯示以下消息:

Welcome to API

現(xiàn)在在瀏覽器中打開 HTML 文件并在文本字段中填寫一些詳細(xì)信息。在文件輸入中上傳文件并提交表單。 用于文件上載的消息終結(jié)點(diǎn)。將顯示在瀏覽器上,并且終端將注銷 req.body 的值為 : { }。 這意味著正文解析器無法處理分段格式數(shù)據(jù)。因此,這里需要 Multer。

添加和配置 Multer

現(xiàn)在要添加 Multer,您需要使用 require() 函數(shù)導(dǎo)入它。 我們還需要設(shè)置需要存儲(chǔ)編碼文件的文件夾。這可以通過在 multer 中指定 dest 屬性來配置。因此,在server.js文件的頂部添加以下兩行。

const multer  = require('multer')
const upload = multer({ dest: 'uploads/' })

如果未指定 dest 屬性,則文件將保存在內(nèi)存中,但永遠(yuǎn)不會(huì)寫入磁盤。 現(xiàn)在我們將更改我們的 POST 路由,以支持在 multer 的幫助下存儲(chǔ)文件。 按如下方式更改郵寄路線:

app.post("/upload", upload.single("myFile"), (req, res) => {
    console.log("Body: ", req.body);
    console.log("File: ", req.file);
    res.send("File successfully uploaded.");
});

multer({..}).single() 用于我們想要處理單個(gè)文件的上傳。myFile 是我們?yōu)?HTML 表單的文件輸入標(biāo)記指定的 name 屬性的值。Multer 會(huì)將文本輸入的值保存在 body 對(duì)象中,將文件保存在 file 對(duì)象中。 在上面的代碼中,我們記錄了 req.body 和 req.file 對(duì)象。然后發(fā)送文件已成功上傳的響應(yīng)。

現(xiàn)在,您的最終server.js代碼將變?yōu)椋?/p>

// Import express
const express = require("express");
const multer = require("multer");
const upload = multer({ dest: "uploads/" });
const PORT = process.env.PORT || 3000;
// Create instance of express.
const app = express();
// Include express.json() middleware
app.use(express.json());
// Include express.urlencoded() middleware
app.use(express.urlencoded({ extended: true }));
// Create a GET endpoint for '/' route
app.get("/", (req, res) => {
    res.send("Welcome to API");
});
// Create a POST endpoint for '/upload' route
app.post("/upload", upload.single("myFile"), (req, res) => {
    console.log("Body: ", req.body);
    console.log("File: ", req.file);
    res.send("File successfully uploaded.");
});
// Listen on the specified port.
app.listen(PORT, () => {
    console.log(`Server started on port : ${PORT}`);
});  

現(xiàn)在再次啟動(dòng)服務(wù)器并在瀏覽器中打開 HTML 文件?,F(xiàn)在填寫表格并上傳文件,然后提交。

提交表單后,瀏覽器上將顯示以下消息:

文件已成功上傳。

在終端中,將出現(xiàn)以下日志:

$ node server
Server started on port : 3000
Body:  [Object: null prototype] { firstName: 'John', lastName: 'Doe' }
File:  {
  fieldname: 'myFile',
  originalname: 'Demo.png',
  encoding: '7bit',
  mimetype: 'image/png',
  destination: 'uploads/',
  filename: '6cb17b42bb4625f6b96b0c30f6835d7a',
  path: 'uploads\\6cb17b42bb4625f6b96b0c30f6835d7a',
  size: 889749
}

body 對(duì)象包含作為鍵值對(duì)的文本輸入。file 對(duì)象包含已存儲(chǔ)文件的元數(shù)據(jù)。現(xiàn)在,您將能夠在項(xiàng)目目錄中看到上傳文件夾。在 uploads 文件夾中,將存儲(chǔ)一個(gè)文件,其名稱與 req.file 對(duì)象中的 filename 字段相同。在我們的例子中,它是 6cb17b42bb4625f6b96b0c30f6835d7a。

通常的做法是將文件存儲(chǔ)在服務(wù)器上的某個(gè)目錄中,并將元數(shù)據(jù)或 req.file 對(duì)象保存在數(shù)據(jù)庫(kù)中。這允許輕松獲取和解碼文件以供進(jìn)一步使用。

元數(shù)據(jù)包含以下字段:

關(guān)鍵字描述
擬態(tài)型文件的 MIME 類型
路徑磁盤存儲(chǔ)中已上載文件的完整路徑。
字段名稱表單中指定的字段名稱
目的地文件已保存在磁盤中的文件夾。
文件名磁盤中目標(biāo)中的文件的名稱。
原名用戶計(jì)算機(jī)上的文件的名稱
緩沖區(qū)存儲(chǔ)在內(nèi)存中的整個(gè)文件的緩沖區(qū)。
編碼文件的編碼類型
大小文件大?。ㄒ宰止?jié)為單位)

現(xiàn)在,如果你想對(duì)文件的存儲(chǔ)有更多的控制權(quán),你必須使用 diskStorage 引擎而不是 dest 對(duì)象。

DiskStorage 的使用

要完全控制文件的存儲(chǔ),例如名稱和目標(biāo),您需要使用磁盤存儲(chǔ)引擎。multer diskStorage 可以按如下方式使用:

var storage = multer.diskStorage({   
     destination: function(req, file, cb) { 
	 // destination is used to specify the path of the directory in which the files have to be stored
     cb(null, './uploads');    
   }, 
   filename: function (req, file, cb) { 
// It is the filename that is given to the saved file.
      cb(null , file.originalname);   
   }
});
// Configure storage engine instead of dest object.
const upload = multer({ storage: storage })

磁盤存儲(chǔ)引擎允許操作文件名和目標(biāo)。

  • destination - 它可以作為字符串或函數(shù)給出。如果未指定,則使用操作系統(tǒng)指定的臨時(shí)文件的默認(rèn)目錄。如果將字符串作為目標(biāo),則 Multer 將創(chuàng)建目錄;否則,如果給定了一個(gè)函數(shù),則必須事先創(chuàng)建目錄。
  • filename - 它確定保存在目標(biāo)目錄中的文件的名稱。如果未指定,則給出一個(gè)沒有擴(kuò)展名的隨機(jī)名稱。定義的函數(shù)應(yīng)返回完整的文件名和擴(kuò)展名。

destination 和 filename 函數(shù)采用三個(gè)參數(shù) - 請(qǐng)求對(duì)象 (req)、文件對(duì)象 (file) 和回調(diào)函數(shù) (cb)。 回調(diào)函數(shù)采用兩個(gè)參數(shù):error 和用于保存文件的名稱。在上面的語(yǔ)法中,使用了原始名稱。

讓我們制作一個(gè)示例應(yīng)用程序,其中我們將根據(jù)文件類型將文件保存在兩個(gè)目錄中:圖像和其他目錄。圖像將包含圖像,其他圖像將包含其余文件。文件名將是當(dāng)前日期(以毫秒為單位)與原始名稱和擴(kuò)展名相結(jié)合。

在 uploads 文件夾中制作兩個(gè)目錄圖像和其他目錄。用 server.js 編寫以下代碼。

// Import express
const express = require("express");
const multer = require("multer");
const multerStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    // Get the type of file.
    const ext = file.mimetype.split("/")[0];
    if (ext === "image") {
        // if type is image then store in images folder
      cb(null, "uploads/images");
    } else {
        // In case of not an image store in others
      cb(null, "uploads/others");
    }
  },
  filename: (req, file, cb) => {
    // Combine the Date in milliseconds and original name and pass as filename
    cb(null, `${Date.now()}.${file.originalname}`);
  },
});
// Use diskstorage option in multer
const upload = multer({ storage: multerStorage });
const PORT = process.env.PORT || 3000;
// Create instance of express.
const app = express();
// Include express.json() middleware
app.use(express.json());
// Include express.urlencoded() middleware
app.use(express.urlencoded({ extended: true }));
// Create a GET endpoint for '/' route
app.get("/", (req, res) => {
    res.send("Welcome to API");
});
// Create a POST endpoint for '/upload' route
app.post("/upload", upload.single("myFile"), (req, res) => {
    console.log("Body: ", req.body);
    console.log("File: ", req.file);
    res.send("File successfully uploaded.");
});
// Listen on the specified port.
app.listen(PORT, () => {
    console.log(`Server started on port : ${PORT}`);
});

在上面的代碼中,已經(jīng)配置了 diskStorage,并且 multer 設(shè)置了存儲(chǔ)引擎而不是目標(biāo)對(duì)象。destination 和 filename 函數(shù)已在 diskStorage 配置中定義。目標(biāo)根據(jù)文件類型使用 if-else 確定,文件名將日期和原始名稱連接在一起。

上傳圖像時(shí),我們?cè)诮K端中得到了以下日志:

Body:  [Object: null prototype] { firstName: 'John', lastName: 'Doe' }
File:  {
  fieldname: 'myFile',
  originalname: 'Demo.png',
  encoding: '7bit',
  mimetype: 'image/png',
  destination: 'uploads/images',
  filename: '1667727488632.Demo.png',
  path: 'uploads\\images\\1667727488632.Demo.png',
  size: 889749
}

該文件以我們選擇的名稱保存在 uploads/images 目錄中。

上傳.txt文件時(shí),會(huì)給出以下日志:

Body:  [Object: null prototype] { firstName: 'John', lastName: 'Doe' }
File:  {
  fieldname: 'myFile',
  originalname: 'demo.txt',
  encoding: '7bit',
  mimetype: 'text/plain',
  destination: 'uploads/others',
  filename: '1667727698642.demo.txt',
  path: 'uploads\\others\\1667727698642.demo.txt',
  size: 0
}

該文件以我們選擇的名稱保存在 uploads/others 目錄中。 uploads 目錄現(xiàn)在具有以下結(jié)構(gòu):

因此,diskStorage 可以幫助對(duì)保存文件的目標(biāo)和文件名提供更多控制。

穆爾特的其他選擇

multer 中還有一些其他重要的選項(xiàng)可用于配置文件上傳。

限制:limits 對(duì)象用于提供上傳文件大小的上限、fieldNameSize 和其他字段(如字段、部件等)的數(shù)量。 下面是一個(gè)限制文件大小的小示例:

const upload = multer({
       storage: storage,
       limits : {fileSize : 1000000} // fileSize in bytes
});

limits 對(duì)象可以幫助防止 DOS(拒絕服務(wù))攻擊。

文件過濾器 :此函數(shù)用于決定必須存儲(chǔ)哪些文件以及可以忽略哪些文件。

filefilter的語(yǔ)法:

function fileFilter (req, file, cb) {  
   //  callback function has a boolean passed to decide whether to keep the file or not.
   // To reject this file pass `false`:   
   cb(null, false);
   // To accept the file pass `true`:   
   cb(null, true);   
   // Create error if something goes wrong:   
   cb(new Error('Unhandled Error!')); 
}

假設(shè)我們只想要圖像:

function fileFilter(req, file, cb) {
    const type = file.mimetype.split("/")[0];
    // Check if the type of file is an image.
    if (type === "image") {
        return cb(null, true);
    } else {
        cb("Error: Only Images!");
    }
}

錯(cuò)誤處理

您可以通過自己調(diào)用 multer 中間件并使用附加到 multer 對(duì)象本身的 MulterError 類來處理 multer 中的錯(cuò)誤。

const multer = require('multer')
const upload = multer().single('myFile')
app.post('/upload', function (req, res) {
  upload(req, res, function (err) {
    if (err instanceof multer.MulterError) {
      // A Multer error occurred when uploading.
    } else if (err) {
      // An unknown error occurred when uploading.
    }
    // If no error occurs.
  })
})

JavaScript Maestro 尋求全棧精通?報(bào)名參加我們的全棧課程,發(fā)現(xiàn)前端和后端開發(fā)的交響樂。

上傳多個(gè)文件

我們可以在 .arrays(fieldname[, max_count]) 的幫助下上傳多個(gè)文件??梢陨蟼髅Q為 fieldname 的文件和最多 max_count 個(gè)文件數(shù)。若要處理多個(gè)文件上傳,可以按如下方式更改 POST 端點(diǎn):

app.post("/upload", upload.array("myFile"), (req, res) => {
    // .array() is used to support upload of multiple files.
    console.log("Body: ", req.body);
    console.log("Files: ", req.files);
    res.send("Files successfully uploaded.");
});

對(duì)于多個(gè)文件,file  的標(biāo)記將多個(gè)屬性設(shè)置為 true。

<input type="file" id="myFile" name="myFile" multiple="true" />

發(fā)送多個(gè)文件時(shí),輸出將類似于以下內(nèi)容:

Body:  [Object: null prototype] { firstName: 'John', lastName: 'Doe' }
Files:  [
  {
    fieldname: 'myFile',
    originalname: 'demo.txt',
    encoding: '7bit',
    mimetype: 'text/plain',
    destination: 'uploads/others',
    filename: '1667730445863.demo.txt',
    path: 'uploads\\others\\1667730445863.demo.txt',
    size: 0
  },
  {
    fieldname: 'myFile',
    originalname: 'Demo.png',
    encoding: '7bit',
    mimetype: 'image/png',
    destination: 'uploads/images',
    filename: '1667730445864.Demo.png',
    path: 'uploads\\images\\1667730445864.Demo.png',
    size: 889749
  }
]

files 數(shù)組將包含每個(gè)文件的對(duì)象。

多個(gè)字段

為了接受來自多個(gè)字段的文件,我們可以使用 upload.fields() 函數(shù)來指定字段及其對(duì)應(yīng)的最大計(jì)數(shù)。 下面是一個(gè)示例:

[
  { name: 'field_nameA', maxCount: 1 },
  { name: 'field_nameB', maxCount: 8 }
]

如圖所示,fields 是具有各種字段配置的對(duì)象數(shù)組。

僅接受文本字段

upload.none() 可用于不允許上傳文件。如果使用 .none(),則LIMIT_UNEXPECTED_FILE文件上傳完成。

更新 post 終結(jié)點(diǎn),如下所示:

app.post("/upload", upload.none(), (req, res) => {
  console.log("Body: ", req.body);
  console.log("Files: ", req.files);
  res.send("Files successfully uploaded.");
});

現(xiàn)在嘗試在上傳文件后提交表單,您將看到以下內(nèi)容。

MulterError: Unexpected field

接受所有文件

upload.any() 可用于接受所有類型和大小的文件。

更新 POST 終結(jié)點(diǎn),如下所示:

app.post("/upload", upload.any(), (req, res) => {
  console.log("Body: ", req.body);
  console.log("Files: ", req.files);
  res.send("Files successfully uploaded.");
});

現(xiàn)在,您將能夠上傳任何類型的文件。

結(jié)論

  • Node.js中的 Multer 是一個(gè)中間件,用于輕松處理文件上傳完成后使用的多部分/表單數(shù)據(jù)。
  • 為了獲得最大的效率,Multer 構(gòu)建在 busboy 之上,busboy 是一個(gè)node.js模塊,用于處理請(qǐng)求中傳入的 HTML 表單數(shù)據(jù)。
  • multipart/form-data 是一種內(nèi)容類型,它使瀏覽器以多部分消息的格式對(duì)表單數(shù)據(jù)進(jìn)行編碼。其中的每個(gè)部分都由一個(gè)文本輸入和一個(gè)文件輸入組成,用于表示表單中的每個(gè)字段。
  • dest 對(duì)象配置為設(shè)置要存儲(chǔ)文件的目錄。
  • multer({..}).single() 用于我們想要處理單個(gè)文件的上傳。
  • 為了更好地控制文件的保存,必須使用 diskStorage 引擎。
  • limits 和 fileFilter 用于對(duì)文件施加限制。
  • 穆爾特。MulterError 類可用于錯(cuò)誤處理。
  • 我們可以在 .arrays(fieldname[, max_count]) 的幫助下上傳多個(gè)文件。
  • 為了接受來自多個(gè)字段的文件,我們可以使用 upload.fields() 函數(shù)來指定字段及其相應(yīng)的最大計(jì)數(shù)。

到此這篇關(guān)于Node js 中的 Multer中間件(文件上傳)的文章就介紹到這了,更多相關(guān)Node js Multer內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • NPM 安裝cordova時(shí)警告:npm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher to

    NPM 安裝cordova時(shí)警告:npm WARN deprecated minimatch@2.0.10: Pleas

    這篇文章主要介紹了NPM 安裝cordova時(shí)警告:npm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher to的相關(guān)資料,需要的朋友可以參考下
    2016-12-12
  • 詳解node Async/Await 更好的異步編程解決方案

    詳解node Async/Await 更好的異步編程解決方案

    這篇文章主要介紹了詳解Async/Await 更好的異步編程解決方案,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-05-05
  • Node.js 中使用 async 函數(shù)的方法

    Node.js 中使用 async 函數(shù)的方法

    async是一個(gè)流程控制工具包,提供了直接而強(qiáng)大的異步功能?;贘avascript為Node.js設(shè)計(jì),同時(shí)也可以直接在瀏覽器中使用。
    2017-11-11
  • 究竟什么是Node.js?Node.js有什么好處?

    究竟什么是Node.js?Node.js有什么好處?

    這篇文章主要介紹了究竟什么是Node.js?Node.js有什么好處?,為試圖解釋什么是 Node.js,本文將簡(jiǎn)要介紹一些背景信息:它要解決的問題,它如何工作,如何運(yùn)行一個(gè)簡(jiǎn)單應(yīng)用程序,最后,Node 在什么情況下是一個(gè)好的解決方案,需要的朋友可以參考下
    2015-05-05
  • Nodejs Post請(qǐng)求報(bào)socket hang up錯(cuò)誤的解決辦法

    Nodejs Post請(qǐng)求報(bào)socket hang up錯(cuò)誤的解決辦法

    這篇文章主要介紹了Nodejs Post請(qǐng)求報(bào)socket hang up錯(cuò)誤的解決辦法,本文因少加了headers字段信息導(dǎo)致出現(xiàn)這個(gè)錯(cuò)誤,本文給出了一個(gè)完整的實(shí)現(xiàn)代碼,需要的朋友可以參考下
    2014-09-09
  • 一文詳解Node.js服務(wù)器動(dòng)態(tài)資源處理

    一文詳解Node.js服務(wù)器動(dòng)態(tài)資源處理

    動(dòng)態(tài)資源處理也就是對(duì)數(shù)據(jù)進(jìn)行重新排序來讀寫數(shù)據(jù)庫(kù),讀取反序列化,寫入序列化,這篇文章主要來和大家聊聊Node.js中的服務(wù)器動(dòng)態(tài)資源處理,感興趣的可以了解下
    2024-04-04
  • Windows下快速搭建NodeJS本地服務(wù)器的步驟

    Windows下快速搭建NodeJS本地服務(wù)器的步驟

    本篇文章主要介紹了Windows下快速搭建NodeJS本地服務(wù)器的步驟,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。
    2017-08-08
  • Windows下Node.js安裝及環(huán)境配置方法

    Windows下Node.js安裝及環(huán)境配置方法

    這篇文章主要為大家介紹一下Node.js安裝及環(huán)境配置方法,這也是腳本之家小編發(fā)現(xiàn)的比較詳細(xì)的教程了,從安裝到配置都很詳細(xì),想學(xué)習(xí)Node.js的朋友可以參考一下
    2017-09-09
  • 詳解Node全局變量global模塊

    詳解Node全局變量global模塊

    這篇文章主要介紹了詳解Node全局變量global模塊,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-09-09
  • 淺談Node 異步IO和事件循環(huán)

    淺談Node 異步IO和事件循環(huán)

    這篇文章主要介紹了淺談Node 異步IO和事件循環(huán),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2019-05-05

最新評(píng)論