0

I am using multer for upload profile picture. after I am done and i have the path , i put my image path in img src element , but i get an error at my console:

Failed to load resource: the server responded with a status of 404 (Not Found)

The image elemnt is in the client side , i am using React. my img element looks like:

<img class="round-img" src="http://localhost:5000/public/engage.jpg" alt="">

my multer strategy:

const DIR = './public/';

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, DIR);
    },
    filename: (req, file, cb) => {
        const fileName = file.originalname.toLowerCase().split(' ').join('-');
        cb(null, fileName)
    }
});

var upload = multer({
    storage: storage,
    fileFilter: (req, file, cb) => {
        if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
            cb(null, true);
        } else {
            cb(null, false);
            return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
        }
    }
});

my upload route:

router.post('/upload' ,[auth, upload.single('imageProfile')], async  (req,res) =>{
    try{
        const url = req.protocol + '://' + req.get('host')
        let user= await User.findById(req.user.id);
        const profile = await Profile.findOne({user:req.user.id});
        console.log("The user is : " + user)
        //Update
        if(user)
        {
            user.avatar=url+ '/public/' + req.file.filename
            await user.save();
            return res.json(profile)
        }
    }
    catch(err){
        console.log(err)
    }
})

server.js:

app.use(express.static('public'));

What am i doing wrong?

John Doe
  • 363
  • 1
  • 5
  • 17

2 Answers2

1

The problem solved by add this line at my server.js:

app.use('/public', express.static('public'));

John Doe
  • 363
  • 1
  • 5
  • 17
0

You have a custom filename function, that will transform an original filename like "my file name.png" into "my-file-name" (note the loss of the file extension). So you need to make sure that this exact filename is requested from your html:

<img class="round-img" src="http://localhost:5000/public/my-file-name">

If you want to keep the file extension, there's already a question which addresses this issue: How to store a file with file extension with multer?

eol
  • 23,236
  • 5
  • 46
  • 64
  • Nice, but I'm pretty sure your code will not work for images you've uploaded dynamically. – eol Aug 18 '20 at 16:55