【问题标题】:How to display image by getting from node server?如何通过从节点服务器获取来显示图像?
【发布时间】:2017-02-17 14:51:42
【问题描述】:

我正在尝试显示我的 index.html 中的图像。这被保存在<img 标记中,每当我的服务器调用 index.html 文件时,它所包含的所有文件路径也会通过检查它自己的服务来加载。

js、css 和 html 等所有类型的文件都在加载,但是当涉及到 img 文件时,它没有在浏览器上加载,并且控制台中没有错误。

图像的路径正确。我正在使用 fs.readFile() 加载文件内容类型,该类型设置为 image/png,因为我的图像文件是 .png。

谁能告诉我这里发生了什么?

【问题讨论】:

  • img 标签仅渲染文件类型或 base64 类型的图像。你把你的图片转换成base 64了吗?
  • 是的,我在 fs.readFile() 中使用编码类型 base64
  • 您是否将 base64 字符串转换为缓冲区?比如 var b = new Buffer('SmF2YVNjcmlwdA==', 'base64') var s = b.toString('hex');
  • 我们可以猜测,但如果您在问题本身中包含您的代码,minimal reproducible example,我们可能会想出更好的答案。

标签: html css node.js


【解决方案1】:

感谢Pankaj Jatav,因为html中的img标签是base64解码器,我们的fs.readFile()编码器必须是base64,因为默认节点在fs.readFile或writeFile中有utf-8作为编码器我们不得不提到编码类型作为图片的base64

    fs.readFile(filepath, 'base64', (err, file) => {
        if (err) {
            res.writeHead(500, { 'Content-Type': 'image/png' });
            res.write(err);
            res.end();
            return;
        }
        res.writeHead(200 , { 'Content-Type': 'image/png' });
       res.end(file,'base64');
   });

这对我有用。

【讨论】:

    猜你喜欢
    • 2018-06-02
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    相关资源
    最近更新 更多