【发布时间】:2019-05-20 20:30:45
【问题描述】:
希望这个问题的答案很简单。
所以我正在创建一个基于 MongoDB、Node、Express、React 等的应用程序,但我不知道如何正确设置和显示用户上传后的头像。
我有一个现成的 API 端点用于上传头像,当请求成功上传图片时。 (在 multer 中间件的帮助下)我也将它正确地存储在 MongoDB 中。问题是它目前看起来像这样,我很确定它不应该:
在 Redux 状态:
avatar(pin): "C:\Users\Kuba\Desktop\mern_project\client\public\avatars\uploads\profileAvatar-1558374898723.jpeg"
那么上传图片的路径应该是什么样子,这样我才能在 React 中成功显示它(如果有帮助,请使用 create-react-app 构建)。我应该将上传的图片存储在哪个文件夹中?
这是我的默认头像路径,效果很好,但它只是通过在 React 组件中导入实现的。
avatar(pin): "/static/media/template-avatar2.173d1842.svg"
Client 是前端,在 routes/api/profile.js 中的 API 端点
感谢您的帮助。
下面是路线
router.post(
"/avatar",
passport.authenticate("jwt", { session: false }),
upload.single("avatar"),
(req, res) => {
const errors = {};
// Path to the avatar is in req.file.path
if (!req.file.path) {
errors.avatar = "Wrong file format";
return res.status(404).json(errors);
}
const avatarPath = req.file.path;
Profile.findOne({ user: req.user.id })
.then(profile => {
if (profile) {
Profile.findOneAndUpdate(
{ user: req.user.id },
{ $set: { avatar: avatarPath } },
{ new: true }
)
.then(profile => {
res.json(profile);
})
.catch(err => res.json(err));
} else {
errors.noprofile = "Couldn't find the profile";
res.status(404).json(errors);
}
errors.noprofile = "Couldn't find the profile";
})
.catch(err => res.status(404).json(errors));
} );
混合器设置
const multer = require("multer");
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "./client/src/img/uploads/avatars");
},
filename: (req, file, cb) => {
cb(
null,
file.fieldname + "-" + file.filename + "." + file.mimetype.slice(6)
);
}
});
const fileFilter = (req, file, cb) => {
if (file.mimetype === "image/jpeg" || file.mimetype === "image/png")
cb(null, true);
else {
// reject a file
let errors = {};
cb(
new Error(
(errors.avatar = "Wrong filetype, only png and jpg types are eligible")
),
false
);
}
};
// Upload avatar middleware
const upload = multer({
storage,
limits: {
fileSize: 1024 * 1024 * 2
},
fileFilter
});
编辑:好的,我将 Multer 中的路径更改为相对路径,现在看起来像这样,仍然不起作用。
avatar(pin): "client\src\img\uploads\avatars\avatar-undefined.png"
【问题讨论】:
标签: reactjs mongodb image express path