首页 > 解决方案 > 如何在 MERN 中使用 multer 插入多个图像?

问题描述

我有一个关于 MERN 堆栈的项目。我必须将表单数据上传到我的 MongoDB 数据库中。

表单数据包含文本和文件字段。该表单包含两个文本字段和两个图像字段。

我已成功上传一张图片,但在从两个不同的输入字段上传两张图片时会出错

我在过去两天尝试从以前在堆栈溢出中询问。现在感觉很无助。直到现在我没有得到任何解决方案

请至少指导我如何调试此错误。

[我的错误]

Uncaught (in promise) Error: Request failed with status code 404
    createError createError.js:16
    settle settle.js:17
    onloadend xhr.js:66
createError.js:16

[注册.js(前端)]

const Register = () => {
    const [newUser, setNewUser] = useState({
        school: "",
        address: "",
        photo: "",
        photoone : ""
     
        
    });

    const handleSubmit = (e) => {
        e.preventDefault();
        const formData = new FormData();
        formData.append("school", newUser.school);
        formData.append("photo", newUser.photo);
        formData.append("photoone" , newUser.photoone)
        formData.append("address", newUser.address);
        



        axios({
            method: "post",
            url: "/teacher",
            data: formData,
            headers: { "Content-Type": "multipart/form-data" },
        })
        .then((response) => {
            console.log(response)
          }).then((data) => {
                console.log(data)
         })
    };

    const handleChange = (e) => {
        setNewUser({ ...newUser, [e.target.name]: e.target.value });
    };

    const handlePhoto = (e) => {
        setNewUser({ ...newUser, photo:  e.target.files[0] });
    };

    const handlePhotoone = (e) => {
        setNewUser({ ...newUser, photoone:  e.target.files[0] });
    };
    // const handlepdf = (e) => {
    //     setNewUser({ ...newUser, pdf: e.target.files[0] });
    // };

    return (
        <>
            <div className="container main">
                <div className="row">
                    <div className="col-sm-6 col-md-6 col-lg-6">
                        <form onSubmit={handleSubmit} encType="multipart/form-data">
                            <div class="mb-3">
                                <label  class="form-label">
                                    Your school
                                </label>
                                <input
                                    type="text"
                                    class="form-control"
                                    id="exampleInputPassword1"
                                    id="school"
                                    name="school"
                                    value={newUser.school}
                                    onChange={handleChange}
                                />
                            </div>

                            <div class="input-group mb-3">
                                <input
                                    type="file"
                                    id="pic"
                                    accept=".png, .jpg, .jpeg"
                                    name="photo"                   
                                    onChange={handlePhoto} type="file" class="form-control" id="inputGroupFile02" />
                            </div>

                            <div class="input-group mb-3">
                                <input
                                    type="file"
                                    id="pic"
                                    placeholder="second photo"
                                    accept=".png, .jpg, .jpeg"
                                    name="photoone"                   
                                    onChange={handlePhotoone} type="file" class="form-control" id="inputGroupFile02" />
                            </div>





                            <div class="mb-3">
                                <label for="exampleInputEmail1" class="form-label">
                                    your address
                                </label>
                                <input
                                    type="text"
                                    id="address"
                                    name="address"
                                    value={newUser.address}
                                    onChange={handleChange}
                                    class="form-control"
                                    aria-describedby="emailHelp"
                                />

                              
                            </div>
                            <button
                                value="register"

                                type="submit"
                                class="btn btn-primary"
                            >
                                Submit
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </>
    );
};

[Auth.js(后端)]

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        let schoolname = req.body.school;
        let path = `C:/Users/kumar/Desktop/mern/server/images/${schoolname}`;

        fs.mkdirsSync(path);
        cb(null, path);
        // cb(null, 'images');
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname);

    }
});


const fileFilter = (req, file, cb) => {
    const allowedFileTypes = ['image/jpeg', 'image/jpg', 'image/png'];
    if (allowedFileTypes.includes(file.mimetype)) {
        cb(null, true);
    } else {
        cb(null, false);
    }
}

let upload = multer({ storage, fileFilter });


router.route('/teacher').post(upload.fields([{
    name: "photo", maxCount: 1
}, {
    name: "photoone", maxCount: 1
}
])), (req, res) => {

    const school = req.body.school;
    const photo = req.file.filename
    const photoone = req.file.filename
    const address = req.body.address;


    const newUserData = {
        school,
        photo,
        photoone,
        address,

    }

    const newUser = new Teacher(newUserData);

    newUser.save()
        .then(() => res.json('User Added'))
        .catch((err) => {
            console.log(err);
        });
}

这个怎么解决??谢谢

标签: node.jsreactjsexpressmern

解决方案


请尝试此代码,因为根据我的理解,您正在以错误的方式访问 nodejs 中的文件,因为当我们在单个请求中上传多个文件时,然后访问文件如下:

const cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', cpUpload, function (req, res, next) {
  // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
  //
  // e.g.
  //  req.files['avatar'][0] -> File
  //  req.files['gallery'] -> Array
  //
  // req.body will contain the text fields, if there were any
})

请用此代码替换您的路线代码:

router.route('/teacher').post(upload.fields([{
    name: "photo", maxCount: 1
}, {
    name: "photoone", maxCount: 1
}
])), (req, res) => {

    const school = req.body.school;
    const photo = req.files['photo'][0].filename
    const photoone = req.files['photoone'][0].filename
    const address = req.body.address;


    const newUserData = {
        school,
        photo,
        photoone,
        address,

    }

    const newUser = new Teacher(newUserData);

    newUser.save()
        .then(() => res.json('User Added'))
        .catch((err) => {
            console.log(err);
        });
}

推荐阅读