node.js - Multer 没有将文件上传到目标文件夹 nd req.file 始终未定义
问题描述
我正在建立一个社交媒体网站,并尝试发布图片和一些文字。但是,当我上传图像并发布它时,它并没有被保存。我正在使用 ExpressJS 和 MongooseODM,并在文件中配置了 multer,其中已制作了 Schema for post。有一个控制器可以创建帖子,我试图在其中保存上传图像的路径。但问题是文件没有上传/保存在我定义的位置。此外,req.file 始终未定义,即使文件已加载。以下是文件:-
Post 模型(使用 Mongoose 创建)
const mongoose = require('mongoose');
const multer = require('multer');
const path = require('path');
const POST_IMAGE_PATH = path.join('/uploads/posts/post_images');
const postSchema = mongoose.Schema({
content : {
type : String,
required : true
},
user : {
type : mongoose.Schema.Types.ObjectId, //refers to the users unique object id
ref : 'User'
},
post_image : {
type : String
},
//include the array of all the ids of all comments in the posts schema itself
comments : [
{
type : mongoose.Schema.Types.ObjectId,
ref : 'Comment'
}
],
//including the array of all the ids of like on the post
likes : [
{
type : mongoose.Schema.Types.ObjectId,
ref : 'Like'
}
],
}, {
timestamps : true
});
let storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.join(__dirname, '..', POST_IMAGE_PATH));
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now());
}
});
postSchema.statics.uploadedPostImage = multer({storage : storage}).single('post_image');
postSchema.statics.postImagePath = POST_IMAGE_PATH;
const Post = mongoose.model('Post', postSchema); //creating the Post Schema
module.exports = Post;```
用于创建帖子的控制器
const { query } = require("express");
const Post = require("../models/post");
const Like = require('../models/like');
const Comment = require("../models/comment");
module.exports.create = async function (req, res) {
try {
let post = await Post.create({
content : 'dummy',
user : req.user._id
});
Post.uploadedPostImage(req, res, function(err){
if (err) {
console.log('Multer error : ', err);
}
post.content = req.body.content;
console.log(req.file);
if (req.file) {
//this is saving the path of the uploaded file into the avatar field in user
post.post_image = Post.postImagePath + '/' + req.file.filename;
console.log(req.file);
}
post.save();
});
if(req.xhr){
//to send the users name we need to populate it
post = await post.populate('user', 'name').execPopulate();
return res.status(200).json({
data : {
post : post
},
message : 'Post created!'
})
}
req.flash('success', 'Post published!');
return res.redirect('back');
} catch (err) {
req.flash('Error in creating post', err);
return res.redirect('back');
}
}
我提交的表格
<div id="post-form">
<div id="welcome-user">Welcome, <%= user.name %>!</div>
<form action="/posts/create" id="new-post-form" enctype="multipart/form-data" type="POST">
<textarea id="post-content" name="content" rows="3" cols="30" placeholder="What's on your mind?" required></textarea>
<br/>
<input type="file" id="post_image" name="post_image" placeholder="Add an Image">
<button type="submit">Post</button>
</form>
</div>
解决方案
推荐阅读
- erlang - Erlang 中的 compile(export_all) 和 export([all/0]) 有什么区别?
- css - 将 Bootstrap/Bootstrap-Vue 导入 Scoped CSS
- java - 从服务器读取自己的对象时出现 EOFExeption
- clojure - 有没有更好的方法在 Clojure 中编写这个枢轴函数?
- react-native - 为 DrawerNavigator 的自定义 contentComponent 添加填充以避免覆盖状态栏
- asp.net-mvc - 如何将 reactjs web 应用程序修复为 .net webapi 授权错误
- java - 如何在 javafx 中创建丰富多彩的(某些天)日历(PopupContent)?
- javascript - 如何将带有 SVG 的 div#WareHouse 转换为图像
- javascript - 在 React 中连接异步数据的最佳实践
- ember.js - ember-bootstrap - 渲染“无线电”输入