Home > other >  Multer is grabbing images but it is not saving my files in the correct directory
Multer is grabbing images but it is not saving my files in the correct directory

Time:01-26

I have an express server. When the user goes to make a post request for the profiel. They submit a profile picture. I am trying to use multer to grab that photo/image that is being sent and store it in a folder on the backend directory.

I setup multer but for some reason it is not saving any of the photos that I want it to save locally so that I can retrieve it. How can I fix this issue. Does anyone have an idea on how to go about this.

controller:

const Profile = require("../../models/UserModels/Profiles.js")
const User = require('../../models/UserModels/Users.js')

const multer = require('multer')
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '../../client/images/profile/')
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now()   '-'   Math.round(Math.random() * 1E9)
    cb(null, file.fieldname   '-'   uniqueSuffix)
  }
})
const upload = multer({ storage: storage })
...
  post:(req, res) => {
    console.log(req.body)
    console.log(req.files)
    upload.single(req.files.profile_pic.name) <----------------
    let body = req.body
    Profile.create({
      profile_pic: req.files.profile_pic.name,
      f_name: body.f_name,
      l_name: body.l_name,
      bio: body.bio,
      location: body.location,
      sm_facebook: body.sm_facebook,
      sm_instagram: body.sm_instagram,
      sm_twitter: body.sm_twitter,
      sm_website: body.sm_website,
      followers: body.followers,
      following: body.following,
      photos: body.photos,
      downloads: body.downloads,
      edits: body.edits,
      userId: body.userId
    })
    .then((data) => {
      res.send(data).status(200)
    })
    .catch((err) => {
      console.error(err)
      res.send(err).status(400)
    })
  },

Here is the direcory for this backend: enter image description here

CodePudding user response:

You have to specify the storage path for multer as if you were located on the root folder of the project. So instead of using '../../client/images/profile/' as storage path, you should use: './backend/client/images/profile'.

You'll code should end up as follows:

const multer = require('multer')
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './backend/client/images/profile')
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now()   '-'   Math.round(Math.random() * 1E9)
    cb(null, file.fieldname   '-'   uniqueSuffix)
  }
})
  •  Tags:  
  • Related