简体   繁体   中英

Upload image with Multer and Formik to Mongodb (MERN)

I created app using MERN. Now I'm trying to upload image with Multer and Formik, but req.file returns undefined , and I can't understand why. I'm new in this, but I guess this may cause from JSON.stringify (http.hook) or content-type: application/json . I also tried do this with FormData , but that's not working. Any ideas?

UPDATE: With Postman works good. I think problem is in ui part, input doesn,t pass the file.

app.js

const {Router} = require('express');
const multer = require('multer');
const auth = require('../middleware/auth.middleware');
const Users= require('../models/Users');
const router = Router();

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

const upload = multer({
    storage: storage,
    limits: { fileSize: 10 * 1024 * 1024 }
});


router.post('/create', upload.single('image'), auth, async (req, res) => {
    console.log(req.file);

    try {
        const code = req.body.code;

        const existing = await Users.findOne({code: code});

        if(existing) {
            return res.json({user: existing})
        }

        const user = new Users(req.body);

        await user .save();

        res.status(201).json(user);
    } catch (e) {
        console.log(e);
        res.status(500).json({ message: 'Error: try again.' })
    }
});

http.hook.js

import {useState, useCallback} from 'react';

export const useHttp = () => {
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

    const request = useCallback(async (url, method = 'GET', body = null, headers = {}) => {
        setLoading(true);

        try {
            if(body) {
                body = JSON.stringify(body);
                headers['Content-Type'] = 'application/json';
            }

            const response = await fetch(url, {method, body, headers});
            const data = await response.json();

            if(!response.ok) {
                throw new Error(data.message || 'Something goes wrong')
            }

            setTimeout(() => {
                setLoading(false);
            }, 800);

            return data
        } catch (e) {
            setLoading(false);
            setError(e.message);

            throw e;
        }
    }, []);

    const clearError = useCallback(() => {setError(null)}, []);

    return {loading, request, error, clearError}};

CreateUser.js

import React, {useCallback, useContext, useEffect, useState} from 'react';
import {useHttp} from "../hooks/http.hook";
import Button from "../components/Button/Button";
import {AuthContext} from "../context/auth.context";
import {Formik} from "formik";

export const CreateUser = () => {
    const {token} = useContext(AuthContext);

    const {loading, request} = useHttp();

    const createUser = useCallback(async (body) => {
        try {
            const fetched = await request(`/api/user/create`, 'POST', body, {
                Authorization: `Bearer ${token}`
            });
        } catch (e) {console.log(e)}
    }, []);

    const handleCreate = (values, {resetForm}) => {
        console.log(values);
        createUser(values);
        
        // resetForm({});
    };

    return (
        <div className="wrapper">
            <div className="row">
                <div className="column small-12 text-center color-white mb_45">
                    <div className="custom-headline text text-48 font-bold">
                        <h1>
                            Crate user
                        </h1>
                    </div>
                </div>
            </div>

            
                <Formik
                    enableReinitialize
                    initialValues={{
                        name: '',
                        code: '',,
                        image: null
                    }}
                    onSubmit={handleCreate}
                >
                    {({
                          values,
                          errors,
                          touched,
                          handleBlur,
                          handleChange,
                          handleSubmit,
                          isSubmitting,
                          setFieldValue,
                          resetForm
                      }) => (
                        <form onSubmit={handleSubmit} className="row align-center">
                            <div className="column small-12 large-7">
                                <div className="form-item flex-container align-middle mb_20">
                                    <label className="text text-14 font-semibold font-uppercase text-right small-4">
                                        Photos
                                    </label>
                                    <input id="image" type="file" name="image" className="file_input"
                                           onChange={(event) => {
                                               setFieldValue("image", event.currentTarget.files[0]);
                                           }} />
                                </div>
                            </div>

                            <div className="column small-12 large-7">
                                <div className="form-item flex-container align-middle mb_20">
                                    <label className="text text-14 font-semibold font-uppercase text-right small-4">
                                        Name
                                    </label>
                                    <input
                                        className="text text-17 "
                                        type="text"
                                        name="name"
                                        onChange={handleChange}
                                        onBlur={handleBlur}
                                        value={values.name}
                                    />
                                </div>
                            </div>
                            <div className="column small-12 large-7">
                                <div className="form-item flex-container align-middle mb_20">
                                    <label className="text text-14 font-semibold font-uppercase text-right small-4">
                                        Code
                                    </label>
                                    <input
                                        className="text text-17"
                                        type="text"
                                        name="code"
                                        onChange={handleChange}
                                        onBlur={handleBlur}
                                        value={values.code}
                                    />
                                </div>
                            </div>

                            <div className="column small-12 mt_20">
                                <div className="btn_group flex-container flex-wrap align-middle align-center">
                                    <Button className="btn-lg radius-8" theme="blue"
                                            text={Submit} type="submit"
                                    />
                                </div>
                            </div>
                        </form>
                    )}
                </Formik>
        </div>
    )
};

Wrap out your image file with formData with the multer key "image"

upload.single('image')

on Front-End

const handleCreate = async (values) => {
    try { 
      const body = new FormData();
      body.append( "image", values.image);
      ...
     
    } catch (err) {}
  };

And make sure about your destination path use "dirname"

`${__dirname}/../client/public/uploads/`

Change this according to your directory path

I have 2-3 suggestion, in your app.js file

router.post('/create', upload.single('image'), auth, async (req, res) => {
console.log(req.file);

you should use auth middelware before using upload.single.

and you should send headers with POST request with {content type: multipart/form-data}

OK, I don't know WHY this was cause, but I found solution - I use axios instead of fetch , and of course FormData for uploading images or files, and it works!
Hope this may be helpful for someone else. Thanks for all answers.

const handleCreate = (values, {resetForm}) => {
        const formData = new FormData();

        formData.append('name', values.name);
        formData.append('code', values.code);
        formData.append('image', values.image);

        axios.post('/api/user/create', formData)
             .then(console.log)
             catch(console.error);
    
        resetForm({});
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM