首页 - 安全 - nodejs进阶(4)—读取图片到页面

nodejs进阶(4)—读取图片到页面

2023-09-05 16:14
-->

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

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

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

readImg:function(path,res){
        fs.readFile(path,'binary',function(err,  file)  {
            if  (err)  {
                console.log(err);
                return;
            }else{
                console.log("输出文件");
                    //res.writeHead(200,  {'Content-Type':'image/jpeg'});
                    res.write(file,'binary');
                    res.end();
            }
        });
    }

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

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

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

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




登录:

这是一个段落


样式1



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

-->