skip to Main Content

I have two files, the server file and My register file. So on the server side, I have the following code for the server file

import multer from 'multer';

const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        return cb(null, "public/images")
    },
    filename: function(req, file, cb) {
        return cb(null, `${Date.now()}_${file.originalname}`)
    }
})
const upload = multer({storage:storage})

app.post('/register', upload.single('user_profilepic'), (req, res) => {
    const sql = "INSERT INTO users (`user_firstname`, `user_lastname`, `user_username`, `user_gender`, `user_location`, `user_phone_no`, `user_email`, `user_password`, `user_category`, `user_profilepic`, `user_skill`) VALUES (?)";
    bcrypt.hash(req.body.user_password.toString(), salt, (err, hash) => {
        if (err) return res.json({Error: "Password hashing error!"})
        const values = [
            req.body.user_firstname,
            req.body.user_lastname,
            req.body.user_username,
            req.body.user_gender,
            req.body.user_location,
            req.body.user_phone_no,
            req.body.user_email,
            hash,
            req.body.user_category,
            req.file.filename,
            req.body.user_skill
        ]

        db.query(sql, [values], (err, result) => {
            console.log(req.file.filename)
            if (err) return res.json({Error: "Values Entry Error!"});
            return res.json({Status: "Data Entry Successful"})
        })
    })
});

and this is the code for the register file

import axios from 'axios';

function Register() {

    const [values, setValues] = useState({
        user_firstname: '',
        user_lastname: '',
        user_username: '',
        user_gender: '',
        user_location: '',
        user_phone_no: '',
        user_email: '',
        user_password: '',
        user_category: '',
        user_profilepic: {},
        user_skill: ''
    })

    const navigate = useNavigate();
    const handleSubmit = (event) => {
        event.preventDefault();
        axios.post('http://localhost:5500/register', values)
        .then(res => {
            if (res.data.Status === 'Data Entry Successful') {
                alert("Sign Up Successful!");
                navigate('/login');
            }
            else {
                alert(res.data.Error);
            }
        })
        .catch(err => console.log(err))
    }

<input type='file' name='image' required='required' placeholder='Select Image' onChange={(e) => setValues({...values, user_profilepic: e.target.files[0]})} />

The code works but I am not seeing anything being uploaded to the destination folder in the server and also in the MySQL database. Am not getting an error at all, both from the frontend side and the backend side. Both say that they have compiled successfully. Please help

I was expecting the image to be saved on the localdisk and the file name/path to be saved on the MySQL. Then after being called, the image can be displayed on the frontend with other data

2

Answers


  1. does the web server and the backend server sharing the same scheme, host and port? if not there will be a cors problem, you can create a proxy server in web server to fix it.

    Login or Signup to reply.
  2. You need to sent data as FormData and set content-type to multipart/form-data.

    const handleSubmit = event => {
        event.preventDefault();
        const formData = new FormData();
        Object.entries(values).forEach(([key, value]) => {
            formData.set(key, value);
        });
        axios
            .post('http://localhost:5500/register', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            })
            .then(res => {
                if (res.data.Status === 'Data Entry Successful') {
                    alert('Sign Up Successful!');
                    navigate('/login');
                } else {
                    alert(res.data.Error);
                }
            })
            .catch(err => console.log(err));
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search