如何使用 node js 将图像上传并保存到 mongodb

Posted

技术标签:

【中文标题】如何使用 node js 将图像上传并保存到 mongodb【英文标题】:How to upload and save image to mongodb using node js 【发布时间】:2019-11-21 00:31:12 【问题描述】:

我正在做一个项目,我需要将图像上传并保存到 MongoDB。我使用 NodeJS 作为后端,使用 Angular Material 作为前端。 我正在 TypeScript 中编写节点和角度。这种上传和保存是如何发生的。我也想知道如何使用芦苇和展示它们。

【问题讨论】:

也许这会有所帮助:) ***.com/q/70483002/17763158 【参考方案1】:

查看Multer

使用示例

store.js

import multer from 'multer';

const storage = multer.diskStorage(
    destination: function (req, file, cb) 
        const path = process.cwd() + '\\uploads';
        cb(null, path);
    ,
    filename: function (req, file, cb) 
        cb(null, `file-$Date.now().$file.originalname.split(/[.]+/).pop()`);
    
);


export const UploadHandler = multer(
    storage: storage,
    fileFilter(req, file, callback, acceptFile) 
        if (['image/png'].indexOf(file.mimetype) === -1) 
            return callback(new Error("This File Is Not Supported"), false);
        
        return callback(null, true);
    
);

app.js

import store from './store';

app.post('/upload', store.array('files', 1), function (req, res, next) 
    if(req.files && req.files.length > 0) 
        // files uploaded successfully
    
);

【讨论】:

以上是关于如何使用 node js 将图像上传并保存到 mongodb的主要内容,如果未能解决你的问题,请参考以下文章