Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting req.file when trying to upload file from React to express js using multer

I am trying to uploading image file from react to express . The req.body shows the path of image like :- image: ‘C:\fakepath\capy1.jpg’ but the image cant be accessed using req.file neither its saved in defined location .

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

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

router.post('/postblog' , upload.single('image'),postController.createPost);

async function createPost(req, res) {
    try {
        console.log(req.body);

        const { title, summary, description } = req.body;
        console.log(req.file);
        const token = req.cookies.token;

        const decodedData = await jwt.decode(token);

        const blog = new postModel({ title: title, summary: summary, description: description, author: decodedData.username , image : req.file});

        await blog.save();

        console.log(blog);

        return res.status(200).json({ "message": "blog created" });
    }

    catch (error) {
        console.log(error);
        return res.status(400);
    }
}
async function submitPost() {
        
        const formData = new FormData();

        formData.append('title', post.title);
        formData.append('summary', post.summary);
        formData.append('description', post.description);
        formData.append('image', post.image);

        const options = {
            method: 'POST',
            body: formData,
            credentials: 'include'
        }
        console.log(post);
        console.log(formData);
        var response = await fetch('http://localhost:8000/api/postblog', options).catch(error => console.log(error));
        console.log("sent");
        try {
            response = await response.json();
            if (response.status === 200) {
                const data = await response.json();
                console.log(data);
            }
            else {
                alert('Error creating Post');
            }
        }

        catch (error) {
            console.log(error);
        }

    }

The frontend seems to be working as intentded but i am unable to access the file with req.file . But i am able to access req.body.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you want to use single file upload you have to use "file" keyword. if you want to allow multiple files you have to use "files".

/// in your case change "image" to "file"
router.post('/postblog' , upload.single('file'),postController.createPost);

examples:

router.post(
    "/update-image",
    upload.single("file"),
    controller_appraisal_modules.avatarUpdate
);

/// how to access the file
exports.avatarUpdate = async(req, res) => {
    const file = req.file;
    console.log(file)
}


router.put(
    "/create",
    // since we specified `array` not `single` we have to use req.files instead of req.file
    // @files   -> key name
    // 2        -> max allowed number of files
    // error response formatted as html
    upload.array("files", 2),
    controller_appraisal_modules.createAPI
);

/// how to access the file
exports.createAPI = async(req, res) => {
    const files = req.files;
    console.log(files)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading