簡體   English   中英

當我嘗試使用 multer 在 node.js 中上傳多個文件時出現問題

[英]I have a problem when I tried to upload multiple files in node.js using multer

我正在嘗試構建一個允許我上傳文件的服務 我從單個文件上傳開始,但是當我嘗試上傳多個文件時遇到問題。

簡而言之,我的問題是,如果我想上傳多張圖片,它會出現在存儲文件夾中,而我在我的數據庫中看不到記錄。

單文件上傳記錄示例

在此處輸入圖像描述

多文件上傳記錄示例

在此處輸入圖像描述

但是那些文件保存在我的存儲中

在此處輸入圖像描述

multer中有兩個function:

對於要上傳的單個文件,請使用:

upload.single('avatar')

對於多個文件上傳使用:

upload.array('photos', 12) //here 12 is max number of files to upload.

參考以下示例代碼:

const express = require("express");
const multer = require("multer");
const app = express();
const multerStorage = multer.memoryStorage();
// Filter files with multer if you need
const multerFilter = (req, file, cb) => {
if (file.mimetype.startsWith("image")) {
cb(null, true);
} else {
cb("upload only images.", false);
}
};
const upload = multer({
storage: multerStorage,
fileFilter: multerFilter,
});
app.post('/singleUpload', upload.single('avatar'), function (req, res,
next) {
// req.body will hold the text fields, if there were any
console.log(req.file);//req.file is the `avatar` file. here avatar is
input field name
})
app.post('/multipleUpload', upload.array('photos', 12), function (req,
res, next) {
// req.body will contain the text fields, if there were any
// req.files is array of `photos` files.here avatar is
input field name
console.log(req.files);
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM