使用node.js和Ni框架的图像服务器
我使用 Ni 框架(该框架又使用 Quip)作为节点,其中有一个名为 asset 的控制器,具有用于图像、文件等的方法。
当您访问 domain.com/ 时,images 方法将获取并显示图像。 assets/images/imagename.png
但是,它显示的是图像的原始数据,而不是图像本身。
我已经设置了标题和内容类型。我的代码是:
var Ni = require('../lib/ni'),
mime = require('mime'),
fs = require("fs");
var AssetsController = function(){
this.images = function(req, res, next, fileName) {
var path = './assets/images/'+fileName;
var image = fs.readFile(path, "binary", function(error, data){
if(error) throw error;
res.writeHead(200, {
'Content-Type' : mime.lookup(path),
'Content-Transfer-Encoding' : 'binary'
});
res.send(data);
});
}
}
module.exports = new AssetsController();
I'm using the Ni framework (which in turn uses Quip) for node, within which there is a controller called assets, with methods for images, files etc.
The images method would fetch and display and image when you visit domain.com/assets/images/imagename.png
However it is displaying the raw data for the image, instead of the image itself.
I have set headers and content type. The code I have is:
var Ni = require('../lib/ni'),
mime = require('mime'),
fs = require("fs");
var AssetsController = function(){
this.images = function(req, res, next, fileName) {
var path = './assets/images/'+fileName;
var image = fs.readFile(path, "binary", function(error, data){
if(error) throw error;
res.writeHead(200, {
'Content-Type' : mime.lookup(path),
'Content-Transfer-Encoding' : 'binary'
});
res.send(data);
});
}
}
module.exports = new AssetsController();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在提供图像时使用这段代码并正确显示它们:
I use this piece of code when serving images and it displays them correctly: