首页 > 解决方案 > How can I upload images in node from a POST request

问题描述

I want to store data and images to my mongo DB from a POST request, but I can't figure it out how. In the request body I have JSON structure like this:

{
   "email":"asd@asd.asd",
   "name":"Asd",
   "shrooms":[
      {
         "name":"Agaricus bisporus",
         "time":"Fri Mar 19 11:11:25 GMT+01:00 2021",
         "gps":"46.25098652819107,20.149517092792898",
        "img1":"Base64 Encoded",
        "img2":"Base64 Encoded" 
     },
     {
         "name":"Unknown",
         "time":"Fri Mar 19 11:11:25 GMT+01:00 2021",
         "gps":"46.25098652819107,20.149517092792898",
        "img1":"Base64 Encoded",
        "img2":"Base64 Encoded" 
     }
   ]
}

And based on the shroom names I want to upload the images in separate folders. I have a router :

router.post('/autoUpload/:tourID', ctrlTour.autoUpload);

In tour.component.js I do a lot of stuff with that data, but I don't know how to upload the Base64 Encoded images.

Untill now I just uploaded the file to my website, and the frontend sent multiple requests, and the images were uploaded by multer like this.

router.post('/uploadShroom', uploadShroomImage.single('shroomImg'), ctrlShroom.postShroomImage );
router.post('/uploadNamelessShroom',uploadNamelessShroomImage.single('namelessShroomimg'), ctrlNamelessShroom.postNamelessShroomImage);

I want it to be automatic, so a POST request can do all the work. Is there any way to call this middleware from a controller class, or how should I upload multile images to multiple paths?

标签: javascriptnode.jsexpressmultermulter-gridfs-storage

解决方案


此处正确的方法是将图像保存在云存储中,例如 aws s3 并将其位置保存在 mongo db 中,而不是尝试保存图像。


推荐阅读