简体   繁体   English

当我尝试使用 multer 在 node.js 中上传多个文件时出现问题

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

I'm trying to build a service that allows me to upload files I started with single-file uploading but I have an issue when I try to upload multiple files.我正在尝试构建一个允许我上传文件的服务 我从单个文件上传开始,但是当我尝试上传多个文件时遇到问题。

In short, my problem is that if I want to upload more than one image, it appears in the storage folder and I don't see the records in my DB.简而言之,我的问题是,如果我想上传多张图片,它会出现在存储文件夹中,而我在我的数据库中看不到记录。

Example of single-file upload record单文件上传记录示例

在此处输入图像描述

Example of multi-file upload record多文件上传记录示例

在此处输入图像描述

But those files are saved on my storage但是那些文件保存在我的存储中

在此处输入图像描述

There are two function in multer: multer中有两个function:

For single file to upload use:对于要上传的单个文件,请使用:

upload.single('avatar')

For multiple file to upload use:对于多个文件上传使用:

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

Refer to the following sample code:参考以下示例代码:

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