使用文件系统显示带有图像的html [英] Displaying html with images using fs

查看:142
本文介绍了使用文件系统显示带有图像的html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我找到了另一个答案,其中使用fs.readFile直接检索html文件,其中图像已经在其中,但在本例中我需要为每个图像构建一个html

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

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/");

推荐答案

好的,我找到了丢失的内容。如果您像我一样不了解服务器,这可能会有所帮助。

<img src="http://localhost:8888/image/jpeg/campus1.jpg">

当服务器读取图像src时,它发送一个带有url/image/jpeg/campus1.jpg的GET请求。目前,服务器可以显示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);

我希望编程不要总是需要我的脑袋移位,事情并不总是有意义的,我有时不明白为什么人们会这样设计东西。但是,爱情并不总是那么容易。祝大家玩得愉快!

这篇关于使用文件系统显示带有图像的html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆