zoukankan      html  css  js  c++  java
  • nodejs进阶(4)—读取图片到页面

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

    先准备一张图片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进阶为一系列教程,可以单独阅读,之间有一定的关联性,最好能系统的进行学习。)

  • 相关阅读:
    亲历dataguard的一些经验问答题
    [转]ORA-38500: USING CURRENT LOGFILE option not available without stand
    修改npm全局安装模式的路径
    Vue 环境搭建
    Linux下查看系统版本号信息的方法
    每天一个Linux命令(12):su命令
    Ubuntu 首次给root用户设置密码
    适用于Linux的windows子系统
    IDEA的terminal设置成Linux的终端一样
    Windows模拟linux终端工具Cmder+Gow
  • 原文地址:https://www.cnblogs.com/fangsmile/p/6249257.html
Copyright © 2011-2022 走看看