无法使用multer保存图像并做出反应

时间:2021-02-14 18:12:55

标签: reactjs express multer

我正在尝试从 React 组件中的表单向我的数据库发送一些字符串和图像。一切都被保存了,还有图像名称,但文件不在 pubblic/images 文件夹中。我的 req.file 总是未定义,我的数据总是一个空对象

这是 Multer 中间件

//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,
});

这是节点的post请求

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);
    }
});

反应

    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 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 个答案:

答案 0 :(得分:0)

通过更改组件代码并向节点应用发送数据(使用Format()创建)解决。

//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("");
};