问题
Good evening for everyone, I have some trouble with saving my url to mongodb database as string. Because mongo adding extra slash to every part of url. Like this: "localhost:3333\uploads\Untitled1.cpp" but in my console log I have normal result(look at the terminal in the screenshot). Whyy? Please, help
let storage = multer.diskStorage({
destination: (req, file, cb) =>{
cb(null, '/uploads')
},
filename: (req, file, cb) => {
cb(null, file.originalname)
}
})
let upload = multer({ storage: storage })
let type = upload.single('myFile');
app.post('/upload', type, (req, res) => {
const url = `http://localhost:3333${req.file.path}`;
const image = {
name: req.file.originalname,
url: url
}
console.log(image.url)
const newImage = new Image(image);
newImage.save()
.then (res.json('Картинку додано'))
.catch(err => res.status(400).json(err));
});
回答1:
I assume you're using a Windows operating system which uses back slashes '\' for paths in its filesystem. The web (and Linux-based operating systems) use forward slashes '/' for paths. Therefore ${req.file.path}, which I'm guessing is referencing a file on your computer, is returning a path including back slashes.
You can use String.replace()
with a regular expression to replace the back slashes with forward slashes:
let webPath = req.file.path.replace(/\\/g,'/'))
const url = `http://localhost:3333${webPath}`;
回答2:
I have found the solution. What you need to do is when you are posting/saving your file into db there you need to use replace function and then your path will be saved with forward slash into your DB.
Here is the snippet:
app.post('/upload', upload.single('file'), (req, res, next) => {
const file = new Cluster1({
filePath: req.file.path.replace(/\\/g, '/'),
name: req.file.originalname
});
file.save()
You can see how I am using the replace fucntion to avoid \\
or \
来源:https://stackoverflow.com/questions/58491205/why-mongodb-adding-extra-slash-to-path