Uploading files to react public folder from server using multer

Viewed 22

I am using multer to upload files on my server but to access these files I have to send it to the react public folder. This works fine when running locally on my system but when I host it on heroku the files are not being sent to the desired path. How do I send the file to the frontend when my server is running on a different port?

SERVER:

const fileStorageEngine = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, './public/img')
        // cb(null,"../client/public/img")
    },
    filename: (req, file, cb) => {
        cb(null, file.originalname);
    },
})


const fileStorageEngineTwo = multer.diskStorage({
    destination: (req, file, cb) => {
        // cb(null,'./public/img')
        cb(null, "../client/public/img")
    },
    filename: (req, file, cb) => {
        cb(null, file.originalname);
    },
})

const upload = multer({
    storage: fileStorageEngine
});

const uploadTwo = multer({
    storage: fileStorageEngineTwo
});

const cpUpload = upload.fields([{ name: 'images', maxCount: 1 }, { name: 'uploadedBy' }])
const cpUploadTwo = uploadTwo.fields([{ name: 'images', maxCount: 1 }, { name: 'uploadedBy' }])

app.post('/api/upload', cpUploadTwo, (req, res, next) => {
    console.log(req.files.images[0].filename);

    var today = new Date();
    var yyyy = today.getFullYear();
    let mm = today.getMonth() + 1;
    let dd = today.getDate();

    if (dd < 10) dd = '0' + dd;
    if (mm < 10) mm = '0' + mm;

    today = dd + '/' + mm + '/' + yyyy;
    var data = new Upload({
        photo: req.files.images[0].filename,
        date: today,
        active: 0,
    });
    data.save();
    res.send('Multiple File uploaded successfully');
});



app.get("/api/get/upload", function (req, res) {
    Upload.find(function (err, fileInfo) {
        if (err) {
            res.send(err);
        } else {
            res.send(fileInfo);
        }
    })
})

FRONTEND:

import React, { useState } from 'react'
import "./Uploading.css";




const Uploading=()=>{

    const [fileData, setFileData]= useState();
    const [nameData, setNameData]= useState();
    const [descriptionData, setDescriptionData]= useState();

    const fileChangeHandler = (e)=>{
        setFileData(e.target.files[0]);
    }
    
    const nameChangeHandler = (e)=>{
        setNameData(e.target.value);
    }

    const descriptionChangeHandler = (e)=>{
        setDescriptionData(e.target.value);
    }

    const onSubmitHandler=(e)=>{
        e.preventDefault();

        // Handle file data from the state before sending
        const data=new FormData();
        data.append('images',fileData);
        
        console.log(data);
        fetch("https://iit-notice-board-backend.herokuapp.com/api/upload",{
            method:"POST",
            body: data,
        })
        .then((result)=>{
            console.log("File Sent Successful")
            alert("Upload Successful!");
            // alert.onSubmit('Upload Successful');
        })
        .catch((err)=>{
            console.log(err.message);
        });
    };

    return (
        <div className="main">
            <h2>USER DASHBOARD</h2>
            <div className="container" id="container">

                <div className="form-container personal-in-container">
                    <form onSubmit={onSubmitHandler} >
                        <h1>File Details</h1>

                        <input type="text" onChange={nameChangeHandler} placeholder="Uploaded By" />
                        
                        <input type="file" onChange={fileChangeHandler} placeholder="Choose profile pic" />
                        <input type="text" onChange={descriptionChangeHandler} placeholder="Description" />

                        <button value="Save" >Upload</button>
                    </form>
                </div>
                <div className="overlay-container">
                    <div className="overlay">

                        <div className="overlay-panel overlay-right">
                            <h1>File Upload</h1>
                            <p>Upload all the necessary files here</p>

                        </div>
                    </div>
                </div>
            </div>


        </div>
    )
}

export default Uploading;
0 Answers
Related