2

I am trying to use the request-promise library or anything similar to send files via a post request from node to another machine that is running Node. Using the normal request module I could so something like

var req = request.post(url, function (err, resp, body) {
 if (err) {
    console.log('Error!');
  } else {
    console.log('URL: ' + body);
  }
});
var form = req.form();
form.append('file', '<FILE_DATA>', {
  filename: 'myfile.txt',
  contentType: 'text/plain'
});

This code is from the question: Uploading file using POST request in Node.js however it is not using promises.

Can anyone explain how to do the same thing but with the request-promise library or if there is any other way to promisify this?

Community
  • 1
  • 1
nbroeking
  • 8,360
  • 5
  • 20
  • 40

1 Answers1

6

According to the docs that are linked from the answer you already found, you don't need to use a .form() method on the resulting request object, but can simply pass the form as the formData option to request. You'll be able to do the same with request-promise:

requestPromise.post({url: url, formData: {
    file: {
        value: '<FILE_DATA>',
        options: {
            filename: 'myfile.txt',
            contentType: 'text/plain'
        }
    }
}).then(function(body) {
    console.log('URL: ' + body);
}, function(err) {
    console.log('Error!');
});

Alternatively, request-promise still seems to return request instances (just decorated with then/catch/promise methods), so the form function should still be available:

var req = requestPromise.post(url);
var form = req.form();
form.append('file', '<FILE_DATA>', {
  filename: 'myfile.txt',
  contentType: 'text/plain'
});
req.then(function(body) {
    console.log('URL: ' + body);
}, function(err) {
    console.log('Error!');
});
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • I did try this but I end up with an error : Unhandled rejection RequestError: Error: write after end – nbroeking Jun 14 '16 at 15:36
  • 1
    Which one? Did it work with the non-promisified `request`? And: Is this the exact code you were using? Where does `FILE_DATA` come from? The code I posted should never produce an unhandled rejection. – Bergi Jun 14 '16 at 15:53
  • I have set data let formData = { id: request._id.toString(), file: { value: fs.createReadStream(request.filePath), options: { 'filename': request.fileName, 'contentType': request.mineType } } }; but not able to get the file in another server req.files is getting undefine – Laxman Mali Mar 30 '20 at 03:48
  • @LaxmanMali You might want to [ask a new question](https://stackoverflow.com/questions/ask) where you post the whole code, of both servers – Bergi Mar 30 '20 at 15:33