10

I have a file in memory (in a buffer), it doesn't exist on the file system (so I can't just stream that).

I'm trying to send it to SignServer using HTTP.

Here's how I try to do it:

var formdata = require('form-data'); var form = new formdata();

form.append('workerName', 'PDFSigner');
form.append('data', file_buffer);
// or
// escape(file_buffer.toString('binary'))
// or
// file_buffer.toString('binary') (without escaping)

var request = form.submit('http://localhost:8080/signserver/process', function(err, res) {});

When I try appending file_buffer SignServer says that data is empty:

Status 400 - Missing file content in upload

When I try appending escape(file_buffer.toString('binary')) (as suggested in How do I send a buffer in an HTTP request?) it's the same story.

When I try appending file_buffer.toString('binary') node.js crashes saying:

node: ../src/stream_base.cc:157 int node::StreamBase::Writev(const v8::FunctionCallbackInfo&): Assertion `(offset) <= (storage_size)' failed.

Aborted (core dumped)

How do I correctly send the file (buffer) through HTTP (multipart/form-data) in Node.JS?

Community
  • 1
  • 1
Ivan Rubinson
  • 2,719
  • 4
  • 15
  • 37

1 Answers1

43

You explicitly need to set a filename for the data field, otherwise the buffer isn't uploaded as a file:

form.append('data', file_buffer, { filename : 'document.pdf' });

This is documented (albeit not very clearly) here: https://github.com/form-data/form-data#alternative-submission-methods (scroll down to the fourth example).

robertklep
  • 185,685
  • 31
  • 370
  • 359
  • 2
    According to https://developer.mozilla.org/en-US/docs/Web/API/FormData/append, I believe it should be `form.append('data', file_buffer, 'document.pdf');` – Silvain Nov 03 '19 at 09:34
  • @Silvain actually, both solutions work :) I'm not sure if `form-data` used to require an object, or if it has always supported passing a filename string. – robertklep Nov 04 '19 at 15:47
  • 1
    I was about to look into writing the buffer to a temp file and using fs to get a stream to that file, thanks!!! – Selçuk Cihan Nov 13 '19 at 14:25
  • I agree with @Silvain. Make sure the filename isn't in an object otherwise the file's name would look like this: name: object object – PepperAddict Aug 18 '20 at 21:19
  • @PepperAddict don't confuse the module that we're talking about (`form-data`) with the web standard that @Silvain links to. The module gladly accepts an object as third argument (which is documented behaviour, as I pointed out in my answer). – robertklep Aug 19 '20 at 08:29
  • 2
    @robertklep This is helpful even after 4 years, many thanks! – Matan D Mar 14 '21 at 13:43
  • 1
    My saviour! Thanks! – José Manuel Blasco Jan 10 '22 at 12:00