javascript 无法使用 node.js 和请求保存远程图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26734047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:25:06  来源:igfitidea点击:

Cannot save a remote image with node.js and request

javascriptnode.jsrequest

提问by Alexander T.

I want to save an image with node.js and the request library. So far I have this simple code:

我想用 node.js 和请求库保存图像。到目前为止,我有这个简单的代码:

var request = require('request');
var fs = require('fs');

request('http://upload.wikimedia.org/wikipedia/commons/8/8c/JPEG_example_JPG_RIP_025.jpg', function(error, response, body)
{
    // further logic that decides
    // whether or not the image will be saved

    fs.writeFile('downloaded.jpg', body, function(){});
});

But it doesn't work. The image always arrives corrupt. I assume it's an encoding error but I cannot figure out how to fix this.

但它不起作用。图像总是到达损坏。我认为这是一个编码错误,但我不知道如何解决这个问题。

回答by Alexander T.

var request = require('request'), 
    fs      = require('fs'),
    url     = 'http://upload.wikimedia.org/wikipedia/commons/8/8c/JPEG_example_JPG_RIP_025.jpg';

request(url, {encoding: 'binary'}, function(error, response, body) {
  fs.writeFile('downloaded.jpg', body, 'binary', function (err) {});
});

回答by kaxi1993

var fs = require('fs'),
    request = require('request'),
    url='http://upload.wikimedia.org/wikipedia/commons/8/8c/JPEG_example_JPG_RIP_025.jpg';

request(url).pipe(fs.createWriteStream('downloaded.jpg'));

回答by prayagupd

Here's how I did it using streamand pipe, (I was using expressbut you may not need that)

这是我使用streamand 的方法pipe,(我正在使用,express但您可能不需要)

var express = require('express');
var app = express();
var filesystem = require('fs');
var https = require('https');


var download = function(url, dest, cb) {
   var file = filesystem.createWriteStream(dest);
   var request = https.get(url, function(httpResponse) {
    httpResponse.pipe(file);
    file.on('finish', function() {
      console.log("piping to file finished")
      file.close(cb);  // close() is async, call cb after close completes.
    });
   }).on('error', function(err) { // Handle errors
    filesystem.unlink(dest); // Delete the file async. (But we don't check the result)
    if (cb) cb(err.message);
   });
};

app.get('/image', (req, res) => {
 download('https://lastfm-img2.akamaized.net/i/u/64s/15cc734fb0e045e3baac02674d2092d6.png',
          'porcupine.png', 
           () => {console.log("downloaded to porcupine.png")})
})

When I run using node server.jsand hit the url localhost:3000/image, it will download and save the file to porcupine.pngin the base directory.

当我运行 usingnode server.js并点击 url 时localhost:3000/image,它将下载文件并将其保存到porcupine.png基本目录中。