如何使用multer将图像保存在磁盘上,并将图像路径保存在mongodb上?

时间:2020-10-26 00:33:25

标签: mongodb express multer mern

到目前为止,我设法将图像上传到mongo上,但是我无法将其保存在磁盘上。

反应组件

const handleUploadPhoto = evt => {
    evt.preventDefault();

    const uploads = photos.map(async photo => {
        const formData = new FormData();
        formData.append('photo', photo);

        await axios.post(
            `${baseUrl}/api/photo/upload/${JSON.parse(localStorage.getItem('loggedUser'))._id}`,
            formData,
            { headers: {
                'Content-Type': 'multipart/form-data'
            }},
        );
    });
};

使用Multer设置上传路线

const FILE_PATH = 'uploads';

const storage = multer.diskStorage({
    destination: (req, file, cb) => cb(null, FILE_PATH),
    filename: (req, file, cb) => {
        const newFileName = `${Math.floor(Math.random() * 1000000)}-${file.originalname.split('.')[0]}${path.extname(file.originalname)}`;
        cb(null, newFileName);
    },
});

const upload = multer({
    storage,
    fileFilter (req, file, cb) {
        if (!file.originalname.match(/\.(jpeg\jpg\png)$/)) {
            cb(new Error('Only upload jpg and png files.'));
        }

        cb(undefined, true);
    }
});

router.post('/upload/:userid', upload.single('photo'), uploadPhoto);

和控制器

const { name, data, mimetype } = req.files.photo;

 User
    .findById(req.params.userid)
    .exec((error, user) => {
        if (error || !user) return res.status(404).json({ message: error.message, });

        const newPhoto = new Photo({
            photo: {
                mimetype,
                data,
                path: `${__dirname}/uploads/${name}`,
                name,
            },
            owner: user._id,
        });

        newPhoto.save((error, photo) => {
            if (error) return res.status(401).json({ message: error, });

            user.photos.push(newPhoto._id);
            user.save();

            return res.status(201).json({
                message: `Image created`,
                path: photo.path,
            });
        });
    });

因此,如您所见,我将数据保存为mongodb中的Buffer,我想将图像实际保存在磁盘上,而仅将图像的名称,mymetype和路径(磁盘上的位置)保存在mongodb中。 / p>

1 个答案:

答案 0 :(得分:1)

首先:您正在使用upload.single()来获取上传的文件

router.post('/upload/:userid', upload.single('photo'), uploadPhoto);

upload.single()会将文件附加到req.file而不是req.files。其中,您使用req.files获取了上传文件,该文件用于上传多个文件:

const { name, data, mimetype } = req.files.photo;

第二个:__dirname获取当前文件而不是当前工作目录for more info的路径,因此您不应该使用__dirname,而应使用./。因此,我假设您实际将文件保存到其他目录,但是使用错误的路径保存在Mongo中。

第三:您正在使用multer.diskStorage,该文件会自动将文件保存到磁盘,并且由于您正在使用diskStorage,根据{{3},您无权访问buffer }。阅读文档,显然是因为您在此处使用了错误的上传文件属性:

const { name, data, mimetype } = req.files.photo;

您必须将其替换为:

const { filename, mimetype } = req.file; // don't have access to buffer in diskStorage