проблемы с отправкой jpg через http - node.js - PullRequest
2 голосов
/ 09 декабря 2011

Я пытаюсь написать простой http веб-сервер, который (помимо других функций) может отправить клиенту запрошенный файл.
Отправка обычного текстового файла / файла 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?

1 Ответ

3 голосов
/ 09 декабря 2011

Вот полный пример того, как отправить изображение с 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);
...