0
votes

I'm trying to send some string and an image to my db from a form in React component. Everything is saved, also the image name, but the file is not in the pubblic/images folder. My req.file is alway undefined and my data always an empty object

This is the Multer middleware

//Multer
const path = require("path");
const multer = require("multer");
const store = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, "public/images");
    },

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

//Upload parameters

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

this is the post request of node

router.post("/", upload.single("image"), verify, async (req, res, next) => {
    console.log(req.file);

    const book = new Book({
        title: req.body.title,
        author: req.body.author,
        image: req.body.image,
    });
    try {
        const savedBook = await book.save();
        res.send(savedBook);
    } catch (error) {
        res.send(error);
    }
});

React

    const token = useSelector((state) => state.token.token);
    const data = new FormData();

    //set Cover on change
    const onChange = (e) => {
        console.log(e.target);
        data.append("image", e.target.files[0]);
        console.log(data);
    };

    //Post Register
    const Submit = async (e) => {
        e.preventDefault();
        await axios
            .post(
                "http://localhost:3000/api/book",
                {
                    title: titleInput,
                    author: authorInput,
                    image: data,
                },
                {
                    headers: {
                        "auth-token": token,
                    },
                }
            )
            .then((res) => {
                console.log(res);
                console.log(data);
            })
            .catch((error) => {
                // handle error
                console.log(error);
            });
        setAuthor("");
        setTitle("");
    
    };

Form

<form encType="multipart/form-data">
    <input
        type="text"
        id="title"
        value={titleInput}
        name="title"
        placeholder="title"
        onChange={(e) => {
        setTitle(e.target.value);
        }}
    />
        <input
            type="text"
            id="author"
            value={authorInput}
            name="author"
            placeholder="Author"
            onChange={(e) => {
            setAuthor(e.target.value);
                }}
            />
            <input type="file" name="image" onChange={onChange} />
            <button type="submit" onClick={Submit}>
                Submit
            </button>
            </form>
1

1 Answers

0
votes

Solved by changing the component code and sending data (create with Format()) to the node app.

//Post Register
const Submit = async (e) => {
    e.preventDefault();
    console.log(filename.name);
    const data = new FormData();
    data.append("author", authorInput);
    data.append("title", titleInput);
    data.append("image", filename);
    data.append(
        "imageTitle",
        titleInput.split(" ").join("").toLowerCase() + ".jpg"
    );

    await axios
        .post("http://localhost:3000/api/book", data, {
            headers: {
                "auth-token": token,
            },
        })
        .then((res) => {
            console.log(res);
        })
        .catch((error) => {
            // handle error
            console.log(error);
        });
    setAuthor("");
    setTitle("");
};