【发布时间】:2021-03-21 00:42:47
【问题描述】:
我正在尝试以 django 风格的方式保存图像,其中图像被保存到文件夹中,文件的路径在获取请求中返回。
到目前为止,我有以下图片模型:
const PictureSchema = new mongoose.Schema(
{
image: {
type: String,
required: true,
},
},
{
timestamps: true,
}
);
module.exports = mongoose.model("Picture", PictureSchema);
以及以下观点:
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "data/images");
},
filename: function (req, file, cb) {
cb(null, Date.now() + ".jpg");
},
});
const upload = multer({ storage: storage });
app.post("/upload", upload.single("image"), (req, res) => {
Picture.create({
image: req.file.path,
})
.then((picture) => res.status(201).json(picture))
.catch((err) => res.status(500).json({ error: err.message }));
});
app.get("/", (req, res) => {
Picture.find({}, "-__v")
.then((pictures) => res.status(200).json(pictures))
.catch((err) => res.status(500).json({ error: err.message }));
});
一切正常,文件被保存到一个文件夹中,当我检索它时显示如下:
{
"_id": "5fd0f1d4f81e3f28b0aa70d3",
"image": "data\\images\\1607528916952.jpg",
"createdAt": "2020-12-09T15:48:36.967Z",
"updatedAt": "2020-12-09T15:48:36.967Z",
"__v": 0
}
但我已经明确设置为静态目录,例如:
app.use(express.static("data"));
我如何让它返回带有图像字段的相对路径而不是文件系统内的相对路径的实例?
【问题讨论】:
标签: node.js mongodb express mongoose multer