我們先實現從指定路徑讀取圖片然後輸出到頁面的功能。
先準備一張圖片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裡傳送請求圖片的方法。
<html>
<head></head>
<body>
登入:
<p>這是一個段落</p>
<h1>樣式1</h1>
<img src="./showImg"></img>
</body>
<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進階為一系列教程,可以單獨閱讀,之間有一定的關聯性,最好能系統的進行學習。)