我正在尝试将视频文件上传到Mongo DB。我在前端使用EJS选择视频文件。之后,我使用如下所示的ajax请求将表单数据传递到后端。
$.ajax({
url: '/savepost',
type: 'post',
data: new FormData(this),
processData: false,
contentType: false,
dataType: 'json',
})
/ savepost逻辑如下。在这里console.log(file)会为视频文件获取一个“未定义”的值,同时它也可以与图像文件一起很好地工作。非常感谢使用multer上传视频文件的任何帮助。
router.post('/savepost',upload.single('upload'),function(req,res,next) {
var body = req.body.body;
var file = req.file;
console.log(file);
var userdata = {userID: req.user._id, fullname: req.user.fullname, image: req.user.image};
if(file){
cloudinary.uploader.upload("./public/images/posts/" + file.filename, function (result) {
file.filename = result.secure_url;
async.waterfall([
function (callback) {
var newPost = new Post();
newPost.body = body.trim();
newPost.image = file.filename;
newPost.owner = userdata;
newPost.save((err, data) => {
if (err) res.send({msg: "Something went wrong", success: false});
if (data) callback(null, data);
});
},
function (data, callback) {
User.findOneAndUpdate(
{_id: req.user._id},
{
$push:
{
posts: {
post: data._id,
body: data.body,
image: data.image
}
}
},
(err, user) => {
if (err) res.send({msg: "Something went wrong", success: false});
if (user) res.send({msg: "Data Saved", post: data, success: true});
}
);
}
]);
});
}