How to store image in node backend?

后端 未结 3 790
终归单人心
终归单人心 2021-01-16 06:08

I am using node and express for backend and Mongo DB for storage.I am using multer middleware for storing image,i got a problem and the problem is when i store an image from

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-16 06:22

    It will become easy to store files after converting in string you just have to convert string in image in your frontend

    convert image in to base64 string using this code in your api and also don't forgot to delete file from upload folder

    "img": new Buffer.from(fs.readFileSync(req.file.path)).toString("base64")

    to delete the file

               let resultHandler = function (err) {
                    if (err) {
                        console.log("unlink failed", err);
                    } else {
                        console.log("file deleted");
                    }
                }
    
                fs.unlink(req.file.path, resultHandler);
    

    at your routes import multer

     `multer const multer = require('multer');
      const upload = multer({ dest: __dirname + '/uploads/images' });`
    

    Add upload.single('img') in your request

    router.post('/fellows-details', authorize([Role.ADMIN, Role.USER]), 
                upload.single('img'), usersController.fellowsdetails);
    

提交回复
热议问题