sur*_*dey 2 node.js express multer
我使用 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
}
Run Code Online (Sandbox Code Playgroud)
控制器上的乘法器设置:
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
})
Run Code Online (Sandbox Code Playgroud)
博客模型
// 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);
Run Code Online (Sandbox Code Playgroud)