'facing some issue uploading file and data with multer in express server

I have 2 problems. I am trying to upload an excel file to the server when I upload an excel file I got the file on my console log but the file is not saving into the folder which I declared on my storage variable.

// Middleware
app.use(express.json())
app.use(cors());
app.use(fileupload());
app.use(express.static("files"));
app.use(bodyParser.json({ limit: "50mb" }));
app.use(bodyParser.urlencoded({ limit: "50mb", extended: true, parameterLimit: 50000 }));

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

    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
});

var upload = multer({ storage: storage })

File upload API. The 2nd problem is I have sent some data and a file from frontend. I am getting the file only but on my req.body I got undefined. If I remove the upload.single('file') then I got the other data.

app.post("/upload-excel", upload.single('file'), async (req, res) => {
            const vendor = req.body
            const file = req.files.file;
            const filename = file.name;
            console.log(vendor); 
})

Here is my frontend:

const ProductImport = function () {
    const [file, setFile] = useState<any>();
    const [isLoading, setIsLoading] = useState<boolean>(false);
    const [fileName, setFileName] = useState("");
    const { userDetails } = UseAuth()
    const saveFile = (e) => {
        setFile(e.target.files[0]);
        setFileName(e.target.files[0].name);
    };
    const uploadFile = async (e: any) => {
        e.preventDefault()
        const formData = new FormData();
        formData.append("file", file);
        formData.append("fileName", fileName);
        formData.append("vendor", userDetails.role);
        formData.append("store", userDetails.store);
        formData.append("publisher", userDetails.email);

        fetch('http://localhost:5000/upload-excel', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                if (data.insertedId) {
                    alert('excel Added')
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });

    };
    return (
        <form onSubmit={uploadFile}>
            <label htmlFor="formGroupExampleInput" className="form-label">Example label</label>
            <input type="file" onChange={saveFile} />
            <button type="submit">Upload</button>
        </form>
    )
}

backend folder structure

enter image description here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source