2

私は、(他の機能の中でも)クライアントに要求されたファイルを送信できる単純なhttpWebサーバーを作成しようとしています。
通常のテキストファイル/htmlファイルを送信することは魅力として機能します。問題は画像ファイルの送信にあります。
これが私のコードの一部です(MIME TYPEを解析し、fs 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ですか?

4

1 に答える 1

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.');

アップデート:

util.pumpはしばらくの間廃止されており、ストリームを使用してこれを達成できます。

fs.createReadStream(filePath).pipe(req);
于 2011-12-09T12:40:28.903 に答える