zoukankan      html  css  js  c++  java
  • nodejs服务器读取图片返回给前端(浏览器)显示

     

    1 前言

    项目需要用nodejs服务器给前端传递图片,网上找了好多资料,多数都是怎么在前端上传图片的,然后通过看runoob.com菜鸟教程,发现其实是非常简单,用express框架就行了。

    2 代码

    2.1 用原生的版本(包含了返回网页功能)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    var http = require('http');
    var fs = require('fs');
    var url = require('url');
    // 创建服务器
    http.createServer( function (request, response) { 
       // 解析请求,包括文件名
       var pathname = url.parse(request.url).pathname;
       // 输出请求的文件名
       console.log("Request for " + pathname + " received.");
       // 从文件系统中读取请求的文件内容
       fs.readFile(pathname.substr(1), function (err, data) {
       var urlContent = pathname.substr(1);
       if(urlContent.lastIndexOf("png") > -1){
           if (err) {
             console.log(err);
             // HTTP 状态码: 404 : NOT FOUND
             // Content Type: text/plain
             response.writeHead(404, {'Content-Type': 'text/html'});
          }else{            
             // HTTP 状态码: 200 : OK
             // Content Type: text/plain
             response.writeHead(200, {'Content-Type': 'image/png'});
            var imageFilePath = pathname.substr(1);
            var stream = fs.createReadStream( imageFilePath );
            var responseData = [];//存储文件流
            if (stream) {//判断状态
                stream.on( 'data', function( chunk ) {
                  responseData.push( chunk );
                });
                stream.on( 'end', function() {
                   var finalData = Buffer.concat( responseData );
                   response.write( finalData );
                   response.end();
                });
            }             
          }
       }else if(urlContent.lastIndexOf("html") > -1){
         if (err) {
             console.log(err);
             // HTTP 状态码: 404 : NOT FOUND
             // Content Type: text/plain
             response.writeHead(404, {'Content-Type': 'text/html'});
          }else{            
             // HTTP 状态码: 200 : OK
             // Content Type: text/plain
             response.writeHead(200, {'Content-Type': 'text/html'});           
             // 响应文件内容
             response.write(data.toString());       
          }
          //  发送响应数据
          response.end();
       }else{
         console.log("unSupport Type, Please contact Administrator err url="+urlContent); 
       }    
       });  
    }).listen(80);

     2.2 用Express框架版本

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    var express = require('express');
    var app = express();
     
    app.use(express.static('public'));
     
    app.get('/public/images/*', function (req, res) {
        res.sendFile( __dirname + "/" + req.url );
        console.log("Request for " + req.url + " received.");
    })
      
    app.get('/public/html/index.html', function (req, res) {
       res.sendFile( __dirname + "/" + "/public/html/index.html" );
       console.log("Request for " + req.url + " received.");
    })
     
    //如果访问网页和本地同名,可以使用以下版本
    app.get('/public/html/*.html', function (req, res) {
       res.sendFile( __dirname + "/" + req.url );
       console.log("Request for " + req.url + " received.");
    })
     
    app.get('/public/register', function (req, res) {
       res.sendFile( __dirname + "/" + "/public/html/register.html" );
       console.log("Request for " + req.url + " received.");
    })
     
    var server = app.listen(80, function () {
      console.log('Server running at http://127.0.0.1:80/');
    })
  • 相关阅读:
    Oracle 11g服务详细介绍及哪些服务是必须开启的?
    分析函数Ratio_to_report使用
    在datagrid中,IE浏览器报错:SCRIPT5007: 无法获取属性“rowspan”的值: 对象为 null 或未定义
    身为一个产品经理应该了解自己的本职
    创意思维常用练习方法资料
    思维导图五个关键秘诀
    思维导图与超级记忆力之间的联系
    易让大脑变迟钝的九中习惯
    分享怎样快速阅读的5大方法
    思维导图运用的四个特征
  • 原文地址:https://www.cnblogs.com/juehai/p/9606511.html
Copyright © 2011-2022 走看看