是否有可能在嵌套的对象数组中上传一个图像或多个图像,例如使用multer或其他东西?
我想用form-data存档此响应:
[
{
"name": "name field",
"title": "title field",
"images": [
{
"path": "path to image 1",
"description": "description field 1"
},
{
"path": "path to image 2",
"description": "description field 2"
}
]
}
]
我只能让它像这样工作:
[
{
"name": "name field",
"title": "title field",
"image": "path to image"
}
]
这是我的代码:
route.post('/', upload.single('image'), addCar)
export const addCar = async (req: Request, res: Response): Promise<void> => {
const car = new Car({
name: req.body.name,
image: req.file.path
})
try {
await car.save()
res.status(201).json(car)
} catch (error) {
res.status(500).json({ error: error.message })
}
}
我的模型:
const CarSchema: Schema = new Schema({
name: String,
image: String
})
我想像这样发送请求:
您正在使用upload.single()
,根据文档,它只处理一个文件,并且只填充req.file
。
由于要处理多个图像和字段,因此可以使用upload.fields()
:
route.post('/', upload.fields([...]), addCar)
请注意,您可能必须更改架构以允许多个图像,因为当前image
不是一个数组。