如何使用multer将映像保存在磁盘上以及mongodb上的映像路径?

如何使用multer将映像保存在磁盘上以及mongodb上的映像路径?,mongodb,express,multer,mern,Mongodb,Express,Multer,Mern,到目前为止,我设法使一个图像上传到mongo上,但我不能使它保存在磁盘上 反应成分 const handleUploadPhoto = evt => { evt.preventDefault(); const uploads = photos.map(async photo => { const formData = new FormData(); formData.append('photo', photo); a

到目前为止,我设法使一个图像上传到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,
            });
        });
    });
和控制器

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中的缓冲区,我希望实际将映像保存在磁盘上,并且只保存mongodb上映像的名称、mymetype和路径(磁盘上的位置)。

首先:您使用
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;
第二:
\uuuuDirName
获取当前文件的路径,而不是当前工作目录,因此不应使用
\uuuDirName
,而应使用
/
。因此,我假设您实际将文件保存到另一个目录,但在Mongo中使用了错误的路径

第三:您使用的是
multer.diskStorage
,它会自动将文件保存到磁盘上,而且由于您使用的是
diskStorage
,因此您无法根据需要访问
缓冲区。请阅读文档,因为您在此处使用的上传文件的属性显然是错误的:

const{name,data,mimetype}=req.files.photo;
您必须将其替换为:

const{filename,mimetype}=req.file;//无法访问diskStorage中的缓冲区

是的,伙计,很好的解释。现在可以了。非常感谢。