Saving image with mongoose

后端 未结 4 1143
情歌与酒
情歌与酒 2021-02-19 11:22

I know there are quite a few threads on this topic already, but unfortunately I didn\'t find my answer until now. I use angular.js with the example code from http://angular-js.i

4条回答
  •  再見小時候
    2021-02-19 11:54

    it is getting repetitive but express does not support img upload so we should do this step:

    1. first installing multer or(any thing you like) +plus fs path and sharp (npm module that resize and change the format helps for ease of job
    const sharp = require("sharp");
    const fs = require("fs");
    const path = require("path");
    const multer = require("multer");
    

    I do suggest to read multer docs

    2.we need a form for image upload



    3.little set up for route

    we have one file so we single method and we need tmperory destination for saving file i use a folder called upload in root of my project

    let upload = multer({ dest: "upload/" });
    app.post('/profile', upload.single('avatar'), function (req, res) {
    
      // req.file is the `avatar` file
      // req.body will hold the text fields, if there were any
    
    const buffer = await sharp(
            path.join(__dirname, `../upload/${req.file.filename}`),
          ).png().toBuffer();
     
          const user = await User.findOneAndUpdate(
            { _id: "5ffb8e8b5f31732740314c72" },
            { avatar: buffer },
          );
    })
    

    now with find and update we successfully updated or created a avatar file

    filename is a random string that the buffer named in that folder

    4.go check out your database to see what happened

提交回复
热议问题