简体   繁体   English

在Node.js中按相对路径显示图像

[英]Displaying images by relative path in Node.js

I am building my first Node.js MVC app (native node, not using Express) and having trouble displaying images from my html files via relative their paths. 我正在构建我的第一个Node.js MVC应用程序(本机节点,未使用Express),并且无法通过相对路径显示html文件中的图像。

I'll spare you my server.js and router.js code, but here is my controller code which is basically how Im loading my views: 我将为您省去我的server.js和router.js代码,但这是我的控制器代码,基本上这就是我加载视图的方式:

var fs = require("fs");
var controller = require("controller"); 

var load_view = 'view_home';
var context = { foo : 'bar' };

controller.load_view(res, req, fs, load_view, context);

this gets passed to... 这被传递给...

var url         = require('url');
var Handlebars  = require('handlebars');

function load_view(res, req, fs, view, context, session){

    // Files to be loaded, in order
    var files = [
        'view/elements/head.html',
        'view/elements/header.html',
        'view/' + view +'.html',
        'view/elements/footer.html'
    ];      

    // Start read requests, each with a callback that has an extra
    // argument bound to it so it will be unshifted onto the callback's
    // parameter list
    for(var i=0; i<files.length; ++i) 
        fs.readFile(files[i], handler.bind(null, i));

    var count = 0;

    function handler(index, err, content) {

        // Make sure we don't send more than one response on error
        if(count < 0) return;
        if(err) {
            count = -1;
            console.log('Error for file: ' + files[index]);
            console.log(err);
            res.writeHead(500);
            return res.end();
        }

        // Reuse our `files` array by simply replacing filenames with
        // their respective content
        files[index] = content;


        // Check if we've read all the files and write them in order if
        // we are finished
        if(++count===files.length) {
            res.writeHead(200, { 'Content-Type': 'text/html' });
            for(var i = 0; i < files.length; ++i) {

                var source = files[i].toString('utf8');

                // Handlebars
                var template = Handlebars.compile(source);
                var html = template(context);   

                res.write(html); /* WRITE THE VIEW (FINALLY) */

            }
            res.end();
        }

    } // handler()

} // load()

Finally, here is my html with tag and relative path in the src attribute: 最后,这是我的src属性中带有标记和相对路径的html:

<div class="help">

    <img src="../public/img/test.jpg" />

</div>

My file system as it relates to the above is as follows: 与以上相关的我的文件系统如下:

I am certain the relative path is correct but have tried all combinations of a relative path and even an absolute path. 我确定相对​​路径是正确的,但是已经尝试过相对路径甚至是绝对路径的所有组合。 Still, no image is displayed. 仍然没有图像显示。

Coming from a LAMP background, accessing images in the file tree is trivial but I realize the server is set up much differently here (since I was the one who set it up). 从LAMP背景开始,访问文件树中的图像很简单,但是我意识到这里的服务器设置非常不同(因为我是设置它的人)。

I access other files (like stylesheets) in the filesystem by creating a separate controller to load those files explicitly and access that controller using a URI. 我通过创建一个单独的控制器来显式加载那些文件并使用URI访问该控制器来访问文件系统中的其他文件(如样式表)。 But this approach in impractical for an indeterminate number of images. 但是对于不确定数量的图像,这种方法不切实际。

How do I access & display my images in the filesystem with Node.js? 如何使用Node.js访问和显示文件系统中的图像?

I access other files (like stylesheets) in the filesystem by creating a separate controller to load those files explicitly and access that controller using a URI. 我通过创建一个单独的控制器来显式加载那些文件并使用URI访问该控制器来访问文件系统中的其他文件(如样式表)。

You need to have a controller. 您需要一个控制器。 That's how the code translates the URL that the browser requests into a response. 这就是代码将浏览器请求的URL转换为响应的方式。

But this approach in impractical for an indeterminate number of images. 但是对于不确定数量的图像,这种方法不切实际。

Write a generic one then. 然后写一个通用的。 Convert all URLs that don't match another controller, or which start with a certain path, or which end with .jpg , or whatever logic you like into file paths based on the URL. 将与另一个控制器不匹配,以某个路径开头,以.jpg结尾或您喜欢的任何逻辑的所有URL转换为基于URL的文件路径。

The read the contents of the file and output a suitable HTTP header (including the right content-type) followed by the data. 读取文件的内容,并输出合适的HTTP标头(包括正确的content-type),后跟数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM