I have an express backend project. I have the user submit a photo for his or her profile picture. I have multer setup and everything. When a request comes in from the frontend, I simply want to grab that file from the request and store it in the ./backend/client/images/profile folder.
I am having the issue in when I am calling upload.single() the file is there but for some reason, it is not actually going through the process of setting the stored file name and storing the image. I have a console.log() that is supposed to trigger when the name of the file is being updated, but it is not triggering.
I am not sure why the console.log() is not triggering or the file is not being saved as I want it to be saved. The path is correct but nothing:
controller file:
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, './backend/client/images/profile')
},
filename: function (req, file, cb) {
console.log(file) <------------------- NOT TRIGGERING ---------------
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
cb(null, file.fieldname + '-' + uniqueSuffix)
}
})
const upload = multer({ storaddge: storage })
const profileController = {
get:(req, res) => {
if(req.session.authenticated){
Profile.findOne({
where: {userId: req.session.user.userId}
})
.then((data) => {
res.send(data).status(200)
})
.catch((err) => {
console.error(err)
})
}
},
post:(req, res) => {
console.log(req.body)
console.log(req.files)
upload.single(req.files.profile_pic) <------ tried both
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
})
this is what the files object looks like when it gets to the backend:
{
profile_pic: {
name: 'ThinkstockPhotos-124946816-1-side.width-358.jpg',
data: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff db 00 43 00 05 03 04 04 04 03 05 04 04 04 05 05 05 06 07 0c 08 07 07 07 07 0f 0b 0b 09 ... 56757 more bytes>,
size: 56807,
encoding: '7bit',
tempFilePath: '',
truncated: false,
mimetype: 'image/jpeg',
md5: 'a938825a8aeccfa50b13d269034f0b68',
mv: [Function: mv]
}
}