【发布时间】:2020-04-12 01:14:40
【问题描述】:
这是我的uploadRouter.js,用于将图像发布到服务器:
const express = require('express');
const bodyParser = require('body-parser');
const authenticate = require('../authenticate');
const multer = require('multer');
const cors = require('./cors');
const Images = require('../models/images');
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'public/images');
},
filename: (req, file, cb) => {
cb(null, file.originalname)
}
});
const imageFileFilter = (req, file, cb) => {
if(!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
return cb(new Error('You can upload only image files!'), false);
}
cb(null, true);
};
const upload = multer({ storage: storage, fileFilter: imageFileFilter});
const uploadRouter = express.Router();
uploadRouter.use(bodyParser.json());
uploadRouter.route('/')
.post(cors.corsWithOptions, authenticate.verifyUser, authenticate.verifyAdmin, upload.single('imageFile'),
(req, res) => {
Images.create(req.body)
.then((image) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(req.file);
}, (err) => next(err))
.catch((err) => next(err));
})
这是我的models/image.js 文件:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var imageSchema = new Schema({
fieldname: {
type: String
},
originalname: {
type: String
},
encoding: {
type: String
},
mimetype: {
type: String
},
destination: {
type: String
},
filename: {
type: String
},
path: {
type: Boolean
},
size:{
type: Number
}
}, {
timestamps: true
});
var Images = mongoose.model('Image', imageSchema);
module.exports = Images ;
当我尝试使用 Postman 发布图像时,成功发布后我得到如下结果:
{
"fieldname": "imageFile",
"originalname": "home_header.jpg",
"encoding": "7bit",
"mimetype": "image/jpeg",
"destination": "public/images",
"filename": "home_header.jpg",
"path": "public\\images\\home_header.jpg",
"size": 58277
}
但是当我向 https://localhost:3443/images/ 端点发送 GET 请求时,我得到了这个结果:
[
{
"_id": "5e8ef5fa98c70f30a8986070",
"createdAt": "2020-04-09T10:16:26.796Z",
"updatedAt": "2020-04-09T10:16:26.796Z",
"__v": 0
},
{
"_id": "5e8efb70070f0b39103cba71",
"createdAt": "2020-04-09T10:39:44.196Z",
"updatedAt": "2020-04-09T10:39:44.196Z",
"__v": 0
},
{
"_id": "5e90150dd9812057f81784f3",
"createdAt": "2020-04-10T06:41:17.633Z",
"updatedAt": "2020-04-10T06:41:17.633Z",
"__v": 0
}
]
然后我看不到我需要在客户端知道的其他字段,例如 filename、originalname 等。那么如何将这些额外字段与_id 和createdAt, updatedAt, __v 字段一起存储?
【问题讨论】:
-
您好!在您的 POST 请求处理程序中,尝试使用
req.file而不是req.body调用Image.create,类似于Images.create(req.file).then(...other existing codes...) -
另外,在您的架构中,您有错字:
imageSchema.path : { type: Boolean },而它应该是String。你的GET方法在哪里?你在运行Images.find().then((images) => {...})吗? -
@Tunmee:谢谢。您的帮助解决了我的问题,但我这里还有一个问题:stackoverflow.com/questions/61119340/…
-
@Valijon:谢谢,我更正了,但这里还是有问题:stackoverflow.com/questions/61119340/…
-
请发布您的
GET路线代码
标签: node.js mongodb httpclient express-router