在NodeJS中使用fs.readfile显示图像

时间:2020-03-08 11:46:39

标签: javascript node.js

我有一个简单的脚本,可为自制框架加载CSS(我不是在使用express,而是在使用http) 我的功能如下:

function getStatic(req, res) {

    console.log(req.params);
    if (fs.existsSync('./public/' + req.params.file)) {

        var file = fs.readFileSync('./public/' + req.params.file, 'utf8');


        res.write(file);
        res.end();

    } else {
        res.writeHead(200, {
            "Content-Type": "text/html; charset=utf-8"
        });
        res.write("⚽⚽⚽⚽ 404 - not found ⚽⚽⚽⚽");
        console.log(req);
        res.end('error')
        console.log(req.params);

    }

}

不幸的是,图像以文件下载的形式出现。我在nodejs - How to read and output jpg image?处找到了类似的答案,但是由于将jpg,png以及可能的其他图像类型覆盖到我的代码中,我不确定是否将其集成到我的代码中。

1 个答案:

答案 0 :(得分:0)

您必须设置内容类型,以便浏览器可以正确处理请求的文件。

顺便说一句,这里有一个本地文件包含漏洞,您可以在此了解更多信息:https://en.wikipedia.org/wiki/File_inclusion_vulnerability