【问题标题】:Displaying html with images using fs使用 fs 显示带有图像的 html
【发布时间】:2021-02-13 21:20:19
【问题描述】:

我需要在我的服务器中显示一个 html,其中包含一些文本和内容,这些在这里并不重要,并且 第一张图片在给定的文件夹中找到 作为参数

我找到了另一个答案,其中 fs.readFile 用于直接检索 html 文件,其中图像已经存在,但在这种情况下 我需要为每个图像构建一个 html。。 p>

我试过了,但它没有显示任何图像:

var http = require('http');
const fs = require('fs');

function read_dir(req, res, path="./images") {
    
    let image_urls = fs.readdirSync(path);
    let src = path.split("").slice(1).join("");

    let image = `<img id="image" src="http://localhost:8888${src}/${image_urls[0]}">`;
 
    res.end(image);
}

function onrequest(request, response) {
    // Programs what is going to be sent back to the browser.
    console.log("HTTP request received");

    // Parses command line arguments
    var myArgs = process.argv.slice(2);

    response.writeHead(200, 
        {"Content-Type": 'text/html'}
    );
    response.write(`<h1>SLIDESHOW AREA</h1>`);

    read_dir(request, response, myArgs[0]);
}

// The http.createServer() method turns my computer into an HTTP server.
var server = http.createServer(onrequest);

// The server.listen() method creates a listener on the specified port or path.
// server.listen(port, hostname, backlog, callback);
server.listen(8888);

console.log("Listening on http://localhost:8888/");

【问题讨论】:

    标签: html node.js fs


    【解决方案1】:

    好的,所以我发现了丢失的内容。如果您像我一样对服务器非常了解,这可能会有所帮助。

    &lt;img src="http://localhost:8888/image/jpeg/campus1.jpg"&gt;

    服务器读取图片src时,会发送一个GET请求,url为/image/jpeg/campus1.jpg。现在服务器可以显示 HTML 元素,但不能显示 JPEG 元素,这是基本的。

    这真的很微妙,图像必须从其文件夹中读取,并正确设置才能显示。

    因此,正确的做法是在服务器内部创建一个路由来读取图像并告诉服务器它们的类型为“image/jpeg”。此时,图像已准备好并被烘焙以供 HTML 读取。

    var http = require('http');
    const fs = require('fs');
    
    let routes = { "/": main, "/image": fileRouter }
    
    function main(req, res) {
        res.writeHead(200, {'Content-Type': 'text/html'});
    
        res.write("<h1>HI</h1>");
        res.write("<h2>Here's an image</h2>");
        res.end(`<img src="http://localhost:8888/image/jpeg/campus1.jpg">`);
    }
    
    function fileRouter(req, res) {
        let path = req.url;
        console.log(path);
    
        fs.readFile("."+path, function(err, data) {
            if(err) {
                res.writeHead(500, { 'Content-Type' : 'text/plain' });
                res.end('500 - Internal Error');
            } else {
                res.writeHead(200, { 'Content-Type' : 'image/jpeg' });
                res.end(data);
            }
        });
    }
    
    function onrequest(req, res) {
        //Parse Request
        let url = req.url;
        let route = url.split("/")[1];
        console.log(req.method, req.url);
        
        //Route Request
        if (typeof routes["/" + route] === 'function') { 
            routes["/" + route](req, res);
        } else {
            res.writeHead(404); //not found
            res.end();
        }
    }
    
    var server = http.createServer(onrequest);
    
    server.listen(8888);
    

    我希望编程不需要总是让我的脑袋脱臼,事情并不总是有意义的,我有时不明白为什么人们会这样设计东西。但好吧,爱情也并不总是那么容易。祝大家有个愉快的一天!

    【讨论】:

    • 很好的答案,是的,编程通常很愚蠢。这么多系统,很难解释如何协同工作。在过去,您可以更轻松地向后工作。现在一切都非常复杂。您的程序可能会中断,并且可能需要深入 3-4 层才能解决。祝你好运。
    【解决方案2】:

    此标签&lt;img id="image" src="http://localhost:8888${src}/${image_urls[0]}"&gt; 正在尝试通过"http://localhost:8888${src}/${image_urls[0]}" url 访问您的服务器。

    所以你需要为浏览器提供它才能下载它。

    jpeg 图像使用'Content-type: image/jpeg'header 提供,但在大图像的情况下,您需要进行更复杂的工作,例如缓存、流式传输等;否则页面的加载时间会很容易下降。

    建议使用 cloudinary 等服务来提供此类内容。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 2019-06-13
    • 2015-09-16
    相关资源
    最近更新 更多