如何在节点/请求中上传远程图像?

问题描述:

我想使用 Node 和请求模块将远程图像上传到我自己的服务器.我已经弄清楚如何使用以下代码上传本地图片:

I would like to upload a remote image to my own server using Node and the request module. I've figure out how to upload local images using the following code:

var options = {
    url: 'https://myownserver.com/images'
};
var req = request.post(options , function optionalCallback(err, httpResponse, body) {
  console.log('Upload successful!  Server responded with:', body);
});

var form = req.form();
form.append('file', fs.createReadStream(__dirname + '/testimg.png'));

我需要对此代码进行哪些修改才能上传远程图像?这是我一直在使用的图像:https://www.filepicker.io/api/file/egqDUkbMQlmz7lqKYTZO

What modifications would I need to make to this code to be able to upload a remote image? This is the image I have been working with: https://www.filepicker.io/api/file/egqDUkbMQlmz7lqKYTZO

我尝试在远程 URL 上使用 fs.createReadStream,但没有成功.如果可能,我宁愿不必在将图像上传到我自己的服务器之前将其保存在本地.

I've tried using fs.createReadStream on the remote URL, but was unsuccessful. If possible, I would prefer not having to save the image locally before uploading it to my own server.

这是我与刮板一起使用的一段代码.我在这里使用回调,所以我可以在保存到我的模型时使用它作为位置.我将您图片的位置放在下面,但在我的代码中我使用了 req.body.image.

This is a piece of code I'm using with a scraper. I'm using the callback here so I can use this as the location when saving to my model. I'm putting the location of your image below, but in my code I use req.body.image.

var downloadURI = function(url, filename, callback) {

  request(url)
    .pipe(fs.createWriteStream(filename))
    .on('close', function() {
      callback(filename);
    });
};

downloadURI('https://myownserver.com/images', __dirname + '/testimg.png', function(filename) {
 console.log(done);
}