How to POST image as form data using npm request?
Asked Answered
E

2

6

I have a specific task: I need to download an image from the source URL and upload it to another host via POST request as multipart/form-data. I'm trying to use node.js request library but never succeed. The following code doesn't send anything in the request body.

request.post({
  url: uploadUrl, 
  formData: {
    photo: request(imageUri)
  }
}, function (err) {
  if (err) console.error(err.stack)
});

I have tried posting directly through the form-data library, but it doesn't seem to work neither. How do I solve this without the creation of temp files?

Empathy answered 28/11, 2016 at 21:27 Comment(2)
You need to wait until you have the image data to send in the form data. Once you have the photo from the request(imageUri) which is available from its callback parameter, you can then proceed with the main post.Unblessed
@magreenberg I though I could pipe it somehow? Do you propose to download it into memory entirely and then post?Empathy
E
0

The problem turned out to be that my imageUri had query parameters in it. I think this is a bug in form-data library. Removing query parameters solved the problem.

Empathy answered 25/7, 2017 at 12:19 Comment(0)
U
1

As i said in my comment, you need to wait until you have the image to make the post request. If you wanted to pipe the streams, you could try something like this...

request.get(imageUri).pipe(request.post(uploadUri));

Hope that helps.

Unblessed answered 28/11, 2016 at 21:41 Comment(2)
Thanks, but I have to post the image as form-dataEmpathy
Then you will have to save it locally first.Unblessed
E
0

The problem turned out to be that my imageUri had query parameters in it. I think this is a bug in form-data library. Removing query parameters solved the problem.

Empathy answered 25/7, 2017 at 12:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.