如何在 MongoDB 中格式化 Multer 图像 url
How to format Multer image url in MongoDB
我刚刚通过 multer 上传了图像,它创建了一个存储在 MongoDB 中的 URL 路径。但是,URL 带有双反斜杠,就像在 Postman 中一样:
{
"_id": "5f9aa0ae9b20ba109857bf39",
"userId": "5f72df7795ba152db857dc42",
"name": "Julian Fletcher",
"email": "fletcher@gmail.com",
"imagePath": "\uploads\1603969198016\wifey.JPG",
"label": "Resume Avatar",
"createdAt": "2020-10-29T10:59:58.097Z",
"__v": 0
}
但是当我直接在 Mongodb compass 中检查时,它看起来像这样带有一个反斜杠:
{
"_id": "5f9aa0ae9b20ba109857bf39",
"userId": "5f72df7795ba152db857dc42",
"name": "Julian Fletcher",
"email": "fletcher@gmail.com",
"imagePath": "\uploads03969198016\wifey.JPG",
"label": "Resume Avatar",
"createdAt": "2020-10-29T10:59:58.097Z",
"__v": 0
}
这是我的挑战:我想将双反斜杠 \ 格式化为单正斜杠 /
这是我的多重配置:
const express = require('express');
const fs = require('fs');
const path = require('path');
const multer = require('multer');
// multer configuration
const storage = multer.diskStorage({
destination:function(req,file,cb){
const uploadsDir = path.join(__dirname,'..','public','uploads',`${Date.now()}`)
fs.mkdirSync(uploadsDir)
cb(null,uploadsDir)
},
filename:function(req,file,cb){
cb(null,file.originalname)
}
})
const uploads=multer({storage})
这是我的控制器:
exports.create = asyncHandler(async (req, res, next) => {
const remove = path.join(__dirname,'..','public')
const relPath = req.file.path.replace(remove,'')
const label = req.body.label;
const imagePath = relPath
const _id = req.params.id;
User.findOne({_id: _id}, function(err, photo){
console.log(photo)
if (err) {
console.log('err', err);
res.status(500).send(err);
} else {
const newPhoto = new Photo ({
userId:_id,
name:photo.name,
email:photo.email,
imagePath:relPath,
label:label
});
console.log(`photosDetail before save ${newPhoto}`);
newPhoto.save(function (err, pool) {
if (err) {
console.log(err);
} else {
console.log('image added successfully!');
res.send(pool);
}
});
}
})
})
路线:
router.route('/create/:id')
.post(uploads.single('images'),create)
我已经检查了不同的示例,但仍然找不到解决方案,在这方面确实需要帮助。我想我基本上需要一种方法来删除 URL"const remove = path.join(__dirname,'..','public')" 的一部分并将 \ 更改为 /同时
您的 relPath 变量需要更改
const relPath = req.file.path.replace(remove,'')
改为如下
const relPath = req.file.path.replace(remove,'').replace(/\/g, '/')
在末尾添加的额外 replace
会将所有反斜杠更改为正斜杠。
作为附带改进,您可以将 replace(remove, '')
更改为 slice
const skipCharactersCount = path.join(__dirname,'..','public').length
const relPath = req.file.path.slice(skipCharactersCount)
并且由于这个 skipCharactersCount
永远不会改变,您可以将其保存为函数外部的常量以避免每次都重新计算它。
因此替换代码将是这样的:
const skipCharactersCount = path.join(__dirname,'..','public').length;
exports.create = asyncHandler(async (req, res, next) => {
const relPath = req.file.path.slice(skipCharactersCount).replace(/\/g, '/')
// rest can stay unchanged
我刚刚通过 multer 上传了图像,它创建了一个存储在 MongoDB 中的 URL 路径。但是,URL 带有双反斜杠,就像在 Postman 中一样:
{
"_id": "5f9aa0ae9b20ba109857bf39",
"userId": "5f72df7795ba152db857dc42",
"name": "Julian Fletcher",
"email": "fletcher@gmail.com",
"imagePath": "\uploads\1603969198016\wifey.JPG",
"label": "Resume Avatar",
"createdAt": "2020-10-29T10:59:58.097Z",
"__v": 0
}
但是当我直接在 Mongodb compass 中检查时,它看起来像这样带有一个反斜杠:
{
"_id": "5f9aa0ae9b20ba109857bf39",
"userId": "5f72df7795ba152db857dc42",
"name": "Julian Fletcher",
"email": "fletcher@gmail.com",
"imagePath": "\uploads03969198016\wifey.JPG",
"label": "Resume Avatar",
"createdAt": "2020-10-29T10:59:58.097Z",
"__v": 0
}
这是我的挑战:我想将双反斜杠 \ 格式化为单正斜杠 /
这是我的多重配置:
const express = require('express');
const fs = require('fs');
const path = require('path');
const multer = require('multer');
// multer configuration
const storage = multer.diskStorage({
destination:function(req,file,cb){
const uploadsDir = path.join(__dirname,'..','public','uploads',`${Date.now()}`)
fs.mkdirSync(uploadsDir)
cb(null,uploadsDir)
},
filename:function(req,file,cb){
cb(null,file.originalname)
}
})
const uploads=multer({storage})
这是我的控制器:
exports.create = asyncHandler(async (req, res, next) => {
const remove = path.join(__dirname,'..','public')
const relPath = req.file.path.replace(remove,'')
const label = req.body.label;
const imagePath = relPath
const _id = req.params.id;
User.findOne({_id: _id}, function(err, photo){
console.log(photo)
if (err) {
console.log('err', err);
res.status(500).send(err);
} else {
const newPhoto = new Photo ({
userId:_id,
name:photo.name,
email:photo.email,
imagePath:relPath,
label:label
});
console.log(`photosDetail before save ${newPhoto}`);
newPhoto.save(function (err, pool) {
if (err) {
console.log(err);
} else {
console.log('image added successfully!');
res.send(pool);
}
});
}
})
})
路线:
router.route('/create/:id')
.post(uploads.single('images'),create)
我已经检查了不同的示例,但仍然找不到解决方案,在这方面确实需要帮助。我想我基本上需要一种方法来删除 URL"const remove = path.join(__dirname,'..','public')" 的一部分并将 \ 更改为 /同时
您的 relPath 变量需要更改
const relPath = req.file.path.replace(remove,'')
改为如下
const relPath = req.file.path.replace(remove,'').replace(/\/g, '/')
在末尾添加的额外 replace
会将所有反斜杠更改为正斜杠。
作为附带改进,您可以将 replace(remove, '')
更改为 slice
const skipCharactersCount = path.join(__dirname,'..','public').length
const relPath = req.file.path.slice(skipCharactersCount)
并且由于这个 skipCharactersCount
永远不会改变,您可以将其保存为函数外部的常量以避免每次都重新计算它。
因此替换代码将是这样的:
const skipCharactersCount = path.join(__dirname,'..','public').length;
exports.create = asyncHandler(async (req, res, next) => {
const relPath = req.file.path.slice(skipCharactersCount).replace(/\/g, '/')
// rest can stay unchanged