使用Postman时,文件100%上传到Mongo DB
使用我的应用程序的前端时 - 除图像
外,所有内容都上传到数据库在我的前端,我从
获得了一系列照片const getPhotosHandler = (e) => {
e.target.files
}
在后端我有:
var express = require("express")
var bodyParser = require("body-parser");
var {ObjectID} = require('mongodb');
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
var {mongoose} = require("./db/mongoose");
var {User} = require("./models/users");
var {Post} = require("./models/post");
var app = express();
app.use(bodyParser.json({limit: '50mb'}))
// Býr til nýjan póst í MongoDB
app.post("/newpost", upload.array('photos', 12), (req, res, next) => {
var post = new Post({
title: req.body.title,
userid: req.body.userid,
category: req.body.category,
price: req.body.price,
body: req.body.body,
latloc: req.body.latloc,
lonloc: req.body.lonloc,
tags: req.body.tags,
photos: req.files
});
post.save().then((doc) => {
res.send(doc)
}, (e) => {
res.status(400).send(e)
})
});
当我通过Postman上传时,我得到了预期的结果:照片(5个对象)与帖子中。但每次我尝试通过应用程序的前端来做到这一点我得到:照片(0个对象)
答案 0 :(得分:0)
你无法上传。如果您需要通过ajax请求上传文件。您需要创建FormData();
请阅读这篇文章https://medium.com/ecmastack/uploading-files-with-react-js-and-node-js-e7e6b707f4ef了解更多详情