首页 > 解决方案 > 如何显示来自服务器 Nodejs 的图像?

问题描述

我的图片成功上传到 /myshop/uploads/ 文件夹,但我很难将图片加载到浏览器。这是我的服务器端代码

const storage = multer.diskStorage({
            destination: (req, file, callBack) => {
            callBack(null, 'uploads')
            },
            filename: (req, file, callBack) => {
            callBack(null, Date.now() + '-'+ file.originalname)
            }
     })
    
    var upload = multer({storage: storage})
    
    
    
    //Upload image
    app.post('/api/myshop/photo', upload.single('file'),(req, res, next)=>{
    
    
            const file = req.file
            console.log(req.file.filename);
            if(!file){
            const error = new Error('Please upload a file')
            error.httpStatusCode = 400
            return next(error)
            }
    
            res.send(file)
    });

这是我的文件夹视图

标签: node.js

解决方案


要将文件发送回客户端,可以使用sendFile方法。您需要提供文件的路径。

  //Upload image
    app.post('/api/myshop/photo', upload.single('file'),(req, res, next)=>{
    
            const file = req.file
            console.log(req.file.filename);
            if(!file){
              const error = new Error('Please upload a file')
              error.httpStatusCode = 400
              return next(error)
            }
    
            // send file back to client
            const filePath = req.file.path;
            res.sendFile(filePath);
    });

推荐阅读