使用 (multer) 处理 node.js 中的图像后图像 url 出现问题

problem with url of image after using (multer) to work with image in node.js

我对图像 url 有疑问,这张图像 url 是这样的:

http://192.168.43.106:3000/upload\139585975-e-learning-concept-with-blurred-city-abstract-lights-background.jpg

问题在这里:

/upload\

那些 (\) 引起了很多问题,请问我怎样才能让 url 像这样正常:

http://192.168.43.106:3000/upload/139585975-e-learning-concept-with-blurred-city-abstract-lights-background.jpg

我使用此代码在 app.js 中使用 (multer) 添加图像中间件:我认为问题出在 (diskStorage) 和 (destination)...

const storage = multer.diskStorage({
    destination: (req, file, cb)=>{
   cb(null, 'upload');
    },

    filename: (req, file, cb)=>{
        cb(null, file.originalname);
         }
});
const filter = (req, file, cb)=>{
    if(file.mimetype == "image/jpg" || file.mimetype == "image/jpeg" || file.mimetype == "image/png"){
        cb(null, true)
    }else{
        cb(null, false);
    }
}

const upload = multer({
    storage: storage,
    filter: filter
});
app.post('/service' ,upload.single('file'));
app.use('/upload', express.static('upload'));

此代码发出获取请求以检索包括图像在内的数据 url:

getAllServices : async (req, res)=>{
        try {
        const result = await SERVICES.find();
        res.json(
            {result : result.map(result =>{
                return {
                    id : result._id,
                    name : result.name,
                    file : 'http://192.168.43.106:3000:3000/'+result.file,
                    desc : result.desc,
                    price : result.price,
                    cat : result.cat,
                    url : 'http://192.168.43.106:3000:3000/service/'+result._id
                }
            })
            });
        }catch(err){result.json(err)}
        
        },

由于您使用的是 file.originalname,它指的是文件系统的路径,并且您很可能在 Windows 上,这实际上是预期的行为。

您可以做的是替换 filename:

中的反斜杠
filename: (req, file, cb) => {
    cb(null, file.originalname.replace(/\/g, "/");
}