使用http模块怎么发送一张图片?
发布于 11 年前 作者 codeid 5619 次浏览 最后一次编辑是 8 年前

var server = http.createServer(function(req,res){ res.setHeader(‘Content-Type’,‘text/html’); res.end(‘Hello World’); }); server.listen(3000,‘127.0.0.1’); 可以给浏览器发送字符串,如果我想给浏览器仅仅发送一张图片该怎么做? var server = http.createServer(function(req,res){ res.setHeader(‘Content-Type’,‘image/png’); //假如拿到图片数据,var image,如何发送到浏览器显示呢? }); server.listen(3000,‘127.0.0.1’);

5 回复

你是问上传图片吗? 还是静态服务器?

这里有一个静态文件服务器的例子:

var http = require('http'),
    url = require('url'),
    path = require('path'),
    fs = require('fs');
 
var PORT = 8080,
    mimeTypes = {
     "html": "text/html",
     "jpeg": "image/jpeg",
     "jpg": "image/jpeg",
     "png": "image/png",
     "js": "text/javascript",
     "css": "text/css",
     "txt": "text/plain"
};
 
var server = http.createServer(function(req,res){
    var pathname = __dirname + url.parse(req.url).pathname;
   
    fs.exists(pathname, function(exists){
     var fileSteam,
         mimeType = mimeTypes[path.extname(pathname).split(".")[1]];
     if(!exists){
       res.writeHead(404, {"Content-Type": "text/plain"});
       res.write('This requst URL ' + pathname + ' was not found on this server.');
       res.end();
          return;
        } 
 res.writeHead(200,{"Content-Type": mimeType});	
 fileSteam = fs.createReadStream(pathname);
 fileSteam.pipe(res); 
    });	
});
server.listen(PORT);
console.log('Server runing at port: ' + PORT + '.');

只要输出对应mime类型,然后通过readStream输入流的pipe方法流向res(输出流)

var http = require( ‘http’ ); var fs = require( ‘fs’ ); http.createServer( function ( req, res ) { res.writeHead( 200, { ‘content-type’: ‘image/jpeg’ } ); var cs = fs.createReadStream( ‘./sl.jpg’, { ‘flag’: ‘r’ } ); cs.pipe( res ); //只读流流向输出流 } ).listen( 7878, function () { console.log( ‘server is start’ );//服务器都有静态文件功能 } )

谢谢,搞定了

多谢,搞定了

回到顶部