我的文件夹中有 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/