如何在节点/请求中上传远程图像? [英] How to upload a remote image in Node/request?

查看:87
本文介绍了如何在节点/请求中上传远程图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 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);
}

这篇关于如何在节点/请求中上传远程图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆