zoukankan      html  css  js  c++  java
  • nodeJS基础08:读取图片

    1.读取图片

    //server.js
    var http = require("http");
    var readImage = require("./readImage");
    http.createServer(function(res, res){
        // res.writeHead(200, {"Content-Type":"text/html; charset=uf-8"});
        res.writeHead(200, {"Content-Type":"image/jpeg"});
        if (res.url!=="/favicon.ico") {
            //res.write('hello,world');//不能向客户端输出任何字节,否则会影响图片的输出
            readImage.readImage('./test.png', res); //如果文件路径存在则添加数据,如果不存在则新建文件并且添加数据
            console.log("继续执行");
            //res.end('end'); 在 readImage.readImage方法中已经写过了
        }
    }).listen(8000);
    console.log('Server running at http://127.0.0.1:8000/');
    // readImage.js
    var  fs=  require('fs');
    module.exports={
        readImage: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();
                }
            });
        }
    }; 

    注意:在读取图片的过程不能向页面写入任何东西。

    现在我们能够向浏览器输出文字,或者图片。下一节我们将学习如何向浏览器同时输出文字和图片。

  • 相关阅读:
    Android入门:Button
    Android入门:部署时的常见错误
    to be
    Android入门:单元测试
    忘记 MySQL 的 root 帐号密码该怎么办
    Eclipse开发build path中jar包部署到应用中
    报告两个bug
    本站导引
    一个用Word做报表设计的报表系统windwardreports
    智能互联网
  • 原文地址:https://www.cnblogs.com/noper/p/6246993.html
Copyright © 2011-2022 走看看