如何使用多个文件引用在 mongoose 中上传和检索图像
How to upload and retrieve images in mognoose with multer file references
我正在尝试以 Django 风格的方式保存图像,图像被保存到一个文件夹中,文件的路径在获取请求中 returned。
到目前为止我有以下图片模型:
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"));
如何使用图像字段的相对路径而不是文件系统中的相对路径将其获取到 return 实例?
由于您已经定义了要静态提供的 data
目录,因此您需要使用以下 url:
请求图像
http://<yourHost>:<yourPort>/images/160...44.jpg
如果你想改变这个并且只指定图像的名称,你需要调整你传递给express.static
中间件的路径:
app.use(express.static("data/images"));
现在您可以使用以下方式请求图像 url:
http://<yourHost>:<yourPort>/160...44.jpg
我正在尝试以 Django 风格的方式保存图像,图像被保存到一个文件夹中,文件的路径在获取请求中 returned。
到目前为止我有以下图片模型:
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"));
如何使用图像字段的相对路径而不是文件系统中的相对路径将其获取到 return 实例?
由于您已经定义了要静态提供的 data
目录,因此您需要使用以下 url:
http://<yourHost>:<yourPort>/images/160...44.jpg
如果你想改变这个并且只指定图像的名称,你需要调整你传递给express.static
中间件的路径:
app.use(express.static("data/images"));
现在您可以使用以下方式请求图像 url:
http://<yourHost>:<yourPort>/160...44.jpg