nodejs write raw image data to jpeg file?

后端 未结 2 1684
忘掉有多难
忘掉有多难 2021-02-09 12:57

I am getting data from a get request. The data (in the body of the response) looks something like this:

... ÿÀ���\"�ÿÄ��������������ÿÄ�N��!1\"AQa2q¡#BR±ð3brS²ÁÂÑ         


        
相关标签:
2条回答
  • 2021-02-09 13:24

    Here's an example, which downloads http://upload.wikimedia.org/wikipedia/commons/1/15/Jagdschloss_Granitz_4.jpg to 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();
        });
    });
    
    0 讨论(0)
  • 2021-02-09 13:38

    A slightly shorter version, which uses 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'));
    });
    
    0 讨论(0)
提交回复
热议问题