2011-12-09 38 views
2

我正在嘗試編寫一個簡單的http web服務器,(其中包括其他功能)可以向客戶端發送請求的文件。
發送常規文本文件/ html文件是一種魅力。問題在於發送圖像文件。
這裏是我的代碼的一部分(解析MIME類型,幷包括FS Node.js的模塊後):通過http發送jpg的問題 - node.js

if (MIMEtype == "image") {  
    console.log('IMAGE'); 
    fs.readFile(path, "binary", function(err,data) { 
     console.log("Sending to user: "); 
     console.log('read the file!'); 
     response.body = data; 
     response.end(); 
    }); 
} else { 
    fs.readFile(path, "utf8", function(err,data) { 
     response.body = data ; 
     response.end() ; 
    }); 
}  

爲什麼所有我得到的是一個空白頁,在打開http://localhost:<serverPort>/test.jpg

+1

是你100%確定文件存在'path'?你應該'console.log(path)'並且確保它指向一個存在並且有數據的文件。 – DaveRandom

+0

@DaveRandom - 是的 - 我想提到處理錯誤,而不是假設它已經工作。 –

+0

@DaveRandom是的,我確定它在那裏,並且在調用這段代碼之前,我確定該文件確實存在。 – limlim

回答

3

下面是關於如何在最簡單的方式與Node.js的發送圖像(我的例子是一個GIF文件,但它可以與其他的文件/圖像類型使用)一個完整的例子:

var http = require('http'), 
    fs = require('fs'), 
    util = require('util'), 
    file_path = __dirname + '/web.gif'; 
    // the file is in the same folder with our app 

// create server on port 4000 
http.createServer(function(request, response) { 
    fs.stat(file_path, function(error, stat) { 
    var rs; 
    // We specify the content-type and the content-length headers 
    // important! 
    response.writeHead(200, { 
     'Content-Type' : 'image/gif', 
     'Content-Length' : stat.size 
    }); 
    rs = fs.createReadStream(file_path); 
    // pump the file to the response 
    util.pump(rs, response, function(err) { 
     if(err) { 
     throw err; 
     } 
    }); 
    }); 
}).listen(4000); 
console.log('Listening on port 4000.'); 

UPDATE:

util.pump已被棄用了,而現在,你可以只使用流acomplish此:

fs.createReadStream(filePath).pipe(req); 
+0

我把你的圖像文件改爲我的jpg文件,並且將Content-Type改爲'image/jpeg',但是不會發生。 – limlim

+0

現在我看到stat.size是0 ..爲什麼? – limlim

+0

你使用什麼節點版本?圖像是否可讀?它是腐敗..? – alessioalex