提问者:小点点

上载图像或嵌套数组中的图像


是否有可能在嵌套的对象数组中上传一个图像或多个图像,例如使用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
})

我想像这样发送请求:


共1个答案

匿名用户

您正在使用upload.single(),根据文档,它只处理一个文件,并且只填充req.file

由于要处理多个图像和字段,因此可以使用upload.fields():

route.post('/', upload.fields([...]), addCar)

请注意,您可能必须更改架构以允许多个图像,因为当前image不是一个数组。