我们先实现从指定路径读取图片然后输出到页面的功能。

先准备一张图片imgs/dog.jpg。

file.js里面继续添加readImg方法,在这里注意读写的时候都需要声明'binary'。(file.js 在上一篇文章nodejs进阶3-路由处理中有完整的内容)

 1 readImg:function(path,res){
 2         fs.readFile(path,'binary',function(err,  file)  {
 3             if  (err)  {
 4                 console.log(err);
 5                 return;
 6             }else{
 7                 console.log("输出文件");
 8                     //res.writeHead(200,  {'Content-Type':'image/jpeg'});
 9                     res.write(file,'binary');
10                     res.end();
11             }
12         });
13     }

服务器创建代码如下,注意在发送请求头时需要声明 {'Content-Type':'image/jpeg'}

 1 var  http  =  require('http');  
 2 var  file  =  require('./models/file');  
 3 http.createServer(function  (request,  response)  {  
 4     //response.writeHead(200,  {'Content-Type':  'text/html;  charset=utf-8'});  
 5     response.writeHead(200,  {'Content-Type':'image/jpeg'});  
 6         if(request.url!=="/favicon.ico"){  //清除第2此访问  
 7         console.log('访问');  
 8         //response.write('hello,world');//不能向客户端输出任何字节  
 9         file.readImg('./imgs/dog.jpg',response);  
10         //------------------------------------------------  
11         console.log("继续执行");  
12         //response.end('hell,世界');//end在方法中写过  
13     }  
14 }).listen(8000);  
15 console.log('Server  running  at  http://127.0.0.1:8000/');

运行后在浏览器里可以看到读取后的图片显示出来。

当然我们真正应用时并不会这样使用,下面我们在换一种方式调用图片,在html里发送请求图片的方法。

1 <html>
2 <head></head>
3 <body>
4 登录:
5 <p>这是一个段落</p>
6 <h1>样式1</h1>
7 <img src="./showImg"></img>
8 </body>
9 <html>

我们用login.html继续测试,在里面加入一个img标签,src的值为"./showImg",这样浏览器会发送另外一个请求http://localhost:8000/showImg。

这样我们在router里面再加入一个方法showImg,在这个方法里面调用file文件里的readImg方法(在本文的第一段代码里)

showImg:function(req,res){
        file.readImg('./imgs/dog.jpg',res);
}

我们运行http://localhost:8000/login

 

(nodejs进阶为一系列教程,可以单独阅读,之间有一定的关联性,最好能系统的进行学习。)

 

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!