Multer + Reactjs - Image is not being saved in the folder

I’m trying to upload images with Nodejs, Express, Postgres, Multer and React for frontend. For some reason the image is not being saved in the uploads folder. I’m using beekeeper to check and I can see that when I submit the form containing the image, the image is downloaded. Another weird thing is that the image in beekeeper start with ‘C:\fakepath’.

I appreciate any help.

Backend file:

const express = require('express');
const router = express.Router();
const models = require('../models');
const multer = require('multer');

const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, './uploads/');
  },
  filename: function(req, file, cb) {
    cb(null, Date.now() + file.originalname)
  }
});

const upload = multer({storage: storage})

/* GET all posts */
// GET /api/v1/posts 
router.get('/', function(req, res) {
  models.Post.findAll()
    .then(posts => {
      res.json(posts)
    })
});

// Create new Post
// POST /api/v1/posts
router.post('/', upload.single('photo'), (req, res) => {
  if (!req.body.status || !req.body.date || !req.body.pet_type || !req.body.description || !req.body.location || !req.body.contact || !req.file.path) {
    res.status(400).json({
      error: 'Please, submit all required fields.'
    })
    return;
  }
  models.Post.create({
    status: req.body.status,
    date: req.body.date,
    pet_type: req.body.pet_type,
    description: req.body.description,
    location: req.body.location,
    contact: req.body.contact,
    photo: req.file.path,
    UserId: req.session.user
  })
  .then(post => {
    res.status(201).json(post)
  })
})

module.exports = router;

My app.js in the backend:

const express = require('express');
const router = express.Router();
const models = require('../models');
const multer = require('multer');

const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, './uploads/');
  },
  filename: function(req, file, cb) {
    cb(null, Date.now() + file.originalname)
  }
});

const upload = multer({storage: storage})

/* GET all posts */
// GET /api/v1/posts 
router.get('/', function(req, res) {
  models.Post.findAll()
    .then(posts => {
      res.json(posts)
    })
});

// Create new Post
// POST /api/v1/posts
router.post('/', upload.single('photo'), (req, res) => {
  if (!req.body.status || !req.body.date || !req.body.pet_type || !req.body.description || !req.body.location || !req.body.contact || !req.file.path) {
    res.status(400).json({
      error: 'Please, submit all required fields.'
    })
    return;
  }
  models.Post.create({
    status: req.body.status,
    date: req.body.date,
    pet_type: req.body.pet_type,
    description: req.body.description,
    location: req.body.location,
    contact: req.body.contact,
    photo: req.file.path,
    UserId: req.session.user
  })
  .then(post => {
    res.status(201).json(post)
  })
})

module.exports = router;

Frontend file

import React, { useEffect, useState } from 'react'

export default function Posts() {

    const [ posts, setPosts ] = useState([]);
    const [ status, setStatus ] = useState('');
    const [ date, setDate ] = useState('');
    const [ pet_type, setPet_type ] = useState('');
    const [ description, setDescription] = useState('');
    const [ location, setLocation] = useState('');
    const [ contact, setContact] = useState('');
    const [ photo, setPhoto] = useState('');

useEffect(() => {
    fetch('/api/v1/posts')
    .then(res => res.json())
    .then(data => {
        setPosts(data);

    })
}, [])

const formSubmit = (e) => {
    fetch('/api/v1/posts', {
        method: 'POST',
        body: JSON.stringify({
            status: status,
            date: date,
            pet_type: pet_type,
            description: description,
            location: location,
            contact: contact,
            photo: photo
        }),
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
    .then(res => res.json())
    alert("done")
}

    return (
        <div>
            <h1> Post </h1>
            <form onSubmit={formSubmit} >
            <label>
                        Status: 
                        <input type="text" name="status" value={status} onChange={(e) => {setStatus(e.target.value)}}/>
                    </label> <br/>
                    <label>
                        Date: 
                        <input type="datetime-local" name="date" value={date} onChange={(e) => {setDate(e.target.value)}}/>
                    </label><br/>
                    <label>
                        Type of Pet: 
                        <input type="pet_type" name="pet_type" value={pet_type} onChange={(e) => {setPet_type(e.target.value)}}/>
                    </label><br/>
                    <label>
                        Description: 
                        <input type="text" name="description" value={description} onChange={(e) => {setDescription(e.target.value)}}/>
                    </label><br/>
                    <label>
                        Location: 
                        <input type="text" name="location" value={location} onChange={(e) => {setLocation(e.target.value)}}/>
                    </label><br/>
                    <label>
                        Contact: 
                        <input type="text" name="contact" value={contact} onChange={(e) => {setContact(e.target.value)}}/>
                    </label><br/>
                    <label>
                        Pet photo: 
                        <input type="file" name="photo" value={photo} onChange={(e) => {setPhoto(e.target.value)}}/>
                    </label><br/>
                    <input type="submit" value="Submit" />
            </form>
        </div>
    )
}

Try

e.target.files[0]

instead e.target.value in setPhoto in the FE.

onChange={(e) => {setPhoto(e.target.files[0])}

More info at:

Still didn’t work :confused:

Add some console logs, see what data you are passing to post etc… that is part of programming. Check the errors. No magic