richardgirges / express-fileupload

Simple express file upload middleware that wraps around busboy
MIT License
1.52k stars 259 forks source link

Image not moving to server folder #340

Closed okeze-stephen closed 10 months ago

okeze-stephen commented 1 year ago

I have tried many times design an application for uploading and saving images on database but the each time i tried, the image file is not moving to the server directory. please i need help on how to resolve it.

This is my index.js for my node and Express Backend const express = require('express'); const uploadedFile = require('express-fileupload'); const cors = require('cors');

const app = express(); const port = process.env.PORT || 5000;

app.use(express.json()); app.use(cors()); app.use(uploadedFile());

// Upload Endpoint Request app.post('/upload', (req, res) => { if(req.files === null) { return res.status(400).json({ msg: 'No file to upload'});

}
// name of the input image
const file = req.files.file;
const filePath = __dirname + '/uploads/'+file.name;
// console.log(file);

// use mv() to place the file on the server
file.mv(filePath, function(err) {
    if(err) return res.status(500).send(err);

    res.send('File Uploaded Successfully');

});

/* file.mv(${__dirname}/client/public/uploads/${file.name}, err => { if(err) { console.error(err); return res.status(500).send(err); }

    res.json({ fileName: file.name, filePath: `/uploads/${file.name}` });
});

*/

});

app.listen(port, ()=> console.log(Server Running on PORT:${port}));

Here is my code for react frontend

import React from 'react'; import '../styles/admin_styles/bootstrap.min.css'; import '../styles/admin_styles/responsive.css'; import '../styles/admin_styles/bootstrap-select.css'; import '../styles/admin_styles/perfect-scrollbar.css'; import '../styles/main.css'; import '../styles/styles.css'; import {Row, Col, Form, Button } from 'react-bootstrap'; import { link, useNavigate } from 'react-router-dom'; import { useState, useEffect } from 'react'; import axios from 'axios';

const AddProducts = () => {

//let history = useNavigate();    // use for Navigation on Previous

const [data, setData]=useState({
    // productName: "",
    // productType: "",
    // manufacturer: "",
    // productPrice: "",
    // description: "",
    selectedFile: "",
    selectedFilePreview: null,
    fileUploaded: {},
})

const handleChange=(e)=>{
    setData({ ...data, 
        // productName: e.target.value,
        // productType: e.target.value,
        // manufacturer: e.target.value,
        // productPrice: e.target.value,
        // description: e.target.value,
        selectedFile: e.target.files[0],
        selectedFilePreview: URL.createObjectURL(e.target.files[0]),

    });

}

const submitForm = async (events) =>{
    events.preventDefault();
    const formdata = new FormData();
    // formdata.append('productName', data.productName);
    // formdata.append('productType', data.productType);
    // formdata.append('manufacturer', data.manufacturer);
    // formdata.append('productPrice', data.productPrice);
    // formdata.append('description', data.description);
    formdata.append('product_img', data.selectedFile);

    try {
        const res = await axios.post("http://localhost:8080/productupload",formdata, {
            headers: {
                "Content-Type": "multipart/form-data"
            }
        });

        const { fileName, filePath } = res.data;

        setData({...data, 
            fileUploaded: { fileName, filePath }
            });

    } catch (err) {
        if (err.response.status === 500) {
            console.log(err.response.me);
            // console.log("There was a problem with the server");
        } else {
            console.log(err.response.data.msg);
        }
    }

    // to post to database 

    // if (data.selectedFile != "") {    
    //     console.log(data.selectedFile);
    // }else{
    //     alert("Choose a file to upload");
    // }

};

return (

) }

export default AddProducts;

bhumit070 commented 1 year ago

Hello there you are appending image as product_img from the frontend and accessing as req.files.file in backend so it will be undefined and it will throw an error while using it please fix it and it might work as expected

and if it fixes it please close the issue