nodejs将原始图像数据写入jpeg文件?

时间:2012-02-06 22:18:29

标签: javascript node.js buffer fs

我从get请求中获取数据。数据(在响应正文中)看起来像这样:

... ÿÀ���"�ÿÄ��������������ÿÄ�N��!1"AQa2q¡#BR±ð3brS²ÁÂÑá$ñCDTst¢³&45dÃÒÿÄ������������ÿÄ�-������!1A"Qa¡ðq±ÁÑ2áÿÚ���?�û." """ """ """ """ """ """ """ """ """ """ """ """ """ """ """ """ """ """ """ """ """ """ """ """R1º#ª¥7Jíî½M6îNö ]·!]=Fv­ß`7~qÆee²%·JokkZüCbìþ<ù{ã9öùË®´(%A,Ià�2I?t×bn6wÆù¥V 2SÀ><k5ºÙØ92EhÎçü¨/aÝ!ã|ñþ¥ñßT}U«¦ÒÚµ«xuÕfƳ KØ {ù{ð$·DúBMZÆcp}´R|Mä2ó8üg)·ùôfõ$zXiRÞü}óÆ>,êÚûíR5ý:\ .....

响应标题如下所示:

HTTP/1.1 200 OK
Content-Length: 26965
Access-Control-Allow-Origin: *
Content-Type: image/jpeg; charset=UTF-8
Date: Mon, 06 Feb 2012 21:14:21 GMT
Expires: Mon, 06 Feb 2012 22:14:21 GMT
Cache-Control: public, max-age=3600
Last-Modified: Fri, 13 Feb 2009 23:31:30 GMT
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Server: Dropta Server 1.0
X-Frame-Options: SAMEORIGIN
Connection: close

我想获取作为我的图像数据的正文内容,并将其保存到服务器上的name.jpeg文件中。

我该怎么做?我尝试将缓冲区与fs模块结合使用,但我有点迷失。

由于

2 个答案:

答案 0 :(得分:14)

以下是将http://upload.wikimedia.org/wikipedia/commons/1/15/Jagdschloss_Granitz_4.jpg下载到name.jpeg

的示例
var fs=require('fs');
var http=require('http');

var f=fs.createWriteStream('name.jpeg');

var options={
    host:'upload.wikimedia.org',
    port:80,
    path:'/wikipedia/commons/1/15/Jagdschloss_Granitz_4.jpg'
}

http.get(options,function(res){
    res.on('data', function (chunk) {
        f.write(chunk);
    });
    res.on('end',function(){
        f.end();
    });
});

答案 1 :(得分:7)

稍短的版本,使用Stream.pipe

var http = require('http'),
    fs = require('fs'),
    imgSource = 'http://upload.wikimedia.org/wikipedia/commons/1/15/Jagdschloss_Granitz_4.jpg';

http.get(imgSource, function(res) {
  res.pipe(fs.createWriteStream('wiki.jpg'));
});