node.js - 如何在node.js中顺序显示文件夹的所有图像

标签 node.js image displayobject

我的文件夹中有 51 张图像,如何按顺序显示所有图像?代码如下。

var i = "hamarabajaj_"; 
var p = 0; 
var q = 0; 
var r = ".png"; 
var http = require('http'),
    fs = require('fs'); 

p = p+1; 
q = i+p+r; 
fs.readFile('/home/bidya271/Documents/Health_Monitor/pictures/'+q, function(err, data) {                                  
    if (err) throw err; 
    http.createServer(function(req, res) {
        res.writeHead(200, {'Content-Type': 'image/jpeg'});     
        res.end(data); // Send the file data to the browser.
    }).listen(8124);    
    console.log('Server running at http://localhost:8124/');      
});

最佳答案

我不完全确定你的目标是什么,但是不可能将图像从 HTTP 服务器“串行”发送到客户端。但是,您可以创建一个服务器,它接受客户端的请求并根据需要返回图像。

下面是一个基于图像前缀提供图像的服务器示例:

var express = require("express"),
    app = express(),
    imageDir = __dirname + "/pictures/",
    imageSuffix = "-image.png",
    fs = require("fs");

app.get("/images/:id", function (request, response) {
    var path = imageDir + request.params.id + imageSuffix;

    console.log("fetching image: ", path);
    response.sendFile(path);
});


app.listen(8080);

上面的代码使用Express轻松引导网络服务器;您可以使用 npm install express 安装它。

假设您将图片添加到“图片”文件夹中,您可以通过点击以下 URL 在浏览器中请求图像:

http://localhost:8080/images/0

这将返回pictures/0-image.png处的图像。 /1 将返回 1-image.png 等等。

关于node.js - 如何在node.js中顺序显示文件夹的所有图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25431025/

相关文章:

javascript - express-typescript 项目的文件夹结构

javascript - 如何让 Node.js 在我的服务器上运行?

node.js - Javascript AWS SDK S3上传方法与正文流生成空文件

Android:带有*正确旋转*图像的快速图像 slider

javascript - 在javascript中创建一个 parent child 的数组

javascript - Uncaught ReferenceError : say is not defined

android - 如何将存储在数据库中的图像作为字符串显示为真实图像?

css - 我希望我的(英雄)图像在屏幕尺寸变小时裁剪

r - 以 Shiny 的方式显示来自本地驱动器的 pdf

JavaScript 表格不显示