nodejs伺服器讀取圖片返回給前端(瀏覽器)顯示

信渤網路科技區塊鏈改發表於2018-09-07

 

 

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/`);
})

相關文章