开发者

Image server using node.js and Ni framework

开发者 https://www.devze.com 2023-03-05 04:15 出处:网络
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.

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 = fun开发者_如何学JAVAction(){
    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 use this piece of code when serving images and it displays them correctly:

fs.readFile(path, function(err, data){
    res.writeHead(200, {"Content-Type": "image/png"});
    res.write(data, "binary");
    res.end();
});
0

精彩评论

暂无评论...
验证码 换一张
取 消