多文件上传不显示文件存储路径

multer file upload doesn't show the path where file is stored

我正在使用 node、express 和 multer 在 angular 应用程序中上传文件,同时为数据库提供 mongoDB。当我上传文件时,虽然它正在上传到名为 uploads 的目标文件夹中,我在 index.js 中声明为静态文件夹,但保存文件的路径未显示在数据库中,默认情况下保持空白价值。下面是创建表单时我的数据库的快照,并且还上传了图像,但是位置应保留为空白的 imagePath 字段

{
    "title": "title to check file upload second time",
    "description": "checking file upload check",
    "bodyHtml": "",
    "views": 0,
    "isPublished": true,
    "category": "Drama",
    "author": "",
    "imagePath": "",
    "_id": "5e399bd4de5df134604a662f",
    "blogId": "ZSiEu37z",
    "created": "2020-02-04T16:29:08.000Z",
    "lastModified": "2020-02-04T16:29:08.000Z",
    "__v": 0
}

控制器上的多项设置:

const multer = require('multer')

 const storage = multer.diskStorage({
     destination: function(req, file, cb) {
         cb(null, './uploads/')
     },
     filename: function(req, file, cb) {
         cb(null, Date.now() + file.originalname)
     }
 })

 const upload = multer({storage: storage})
let setRouter = (app) => {
    let baseUrl = appConfig.apiVersion+'/blogs';

app.post(baseUrl+'/create', upload.single('imagePath'), (req, res) => {
    var today = time.now()
    let blogId = shortid.generate()
    let newBlog = new BlogModel({

        blogId: blogId,
        title: req.body.title,
        description: req.body.description,
        imagePath: req.body.imagePath

    }) // end new blog model

    newBlog.save((err, result) => {
        if (err) {
            console.log(err)
            res.send(err)
        } else {
            res.send(result)

        }
    }) // end new blog save
})

博客模型

// importing mongoose module
const mongoose = require('mongoose')
// import schema 
const Schema = mongoose.Schema;

let blogSchema = new Schema(
    {
        blogId: {
            type: String,
            unique: true,
            index: true
        },
        title: {
            type: String,
            default: ''
        },
        description: {
            type: String,
            default: ''
        },
        imagePath: {
            type: String,
            default: ''
        }
    }
)

mongoose.model('Blog', blogSchema);

您可以在上传文件前设置将在您的上传文件夹目录中使用的文件名,只需将该名称保存在mongo

https://expressjs.com/en/resources/middleware/multer.html

在保存 json 对象时在控制器函数内部使用 req.file.path 而不是 req.body.imagePath 作为 imagePath

的值

在控制器内部,在 imagePath 请求对象中写入 REQ.FILE.PATH insted of REQ.BODY.imagePath...{注意:对于“REQ.FILE.PATH”,您不必导入路径模型...}

并且该路径来自您使用 path.join(__dirname, 'foldername');

的 app.js 文件