【问题标题】:Why i can`t see the image after user multer?为什么用户 multer 后我看不到图像?
【发布时间】:2020-12-07 21:34:41
【问题描述】:

我正在使用 multer 上传个人资料图片。 完成并获得路径后,我将图像路径放在 img src 元素中,但我的控制台出现错误:

Failed to load resource: the server responded with a status of 404 (Not Found)

图像元素在客户端,我正在使用 React。 我的 img 元素看起来像:

<img class="round-img" src="http://localhost:5000/public/engage.jpg" alt="">

我的多重策略:

const DIR = './public/';

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, DIR);
    },
    filename: (req, file, cb) => {
        const fileName = file.originalname.toLowerCase().split(' ').join('-');
        cb(null, fileName)
    }
});

var upload = multer({
    storage: storage,
    fileFilter: (req, file, cb) => {
        if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
            cb(null, true);
        } else {
            cb(null, false);
            return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
        }
    }
});

我的上传路线:

router.post('/upload' ,[auth, upload.single('imageProfile')], async  (req,res) =>{
    try{
        const url = req.protocol + '://' + req.get('host')
        let user= await User.findById(req.user.id);
        const profile = await Profile.findOne({user:req.user.id});
        console.log("The user is : " + user)
        //Update
        if(user)
        {
            user.avatar=url+ '/public/' + req.file.filename
            await user.save();
            return res.json(profile)
        }
    }
    catch(err){
        console.log(err)
    }
})

server.js:

app.use(express.static('public'));

我做错了什么?

【问题讨论】:

    标签: node.js reactjs multer


    【解决方案1】:

    通过在我的 server.js 中添加这一行解决的问题:

    app.use('/public', express.static('public'));

    【讨论】:

      【解决方案2】:

      您有一个自定义的filename 函数,它将原始文件名(如“my file name.png”)转换为“my-file-name”(注意文件扩展名的丢失)。所以你需要确保从你的 html 请求这个确切的文件名:

      <img class="round-img" src="http://localhost:5000/public/my-file-name">
      

      如果你想保留文件扩展名,已经有一个问题解决了这个问题:How to store a file with file extension with multer?

      【讨论】:

      • 很好,但我很确定您的代码不适用于您动态上传的图像。
      猜你喜欢
      • 2018-03-05
      • 2020-05-22
      • 1970-01-01
      • 2011-02-12
      • 1970-01-01
      • 2011-06-25
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多