How can I test file-upload with hapi?

Viewed 482

I have this payload format in my hapi route that accepts only multipart/form-data data and the output is set as a stream:

payload: {
        maxBytes: 1024,
        output: 'stream',
        parse: true,
        allow: 'multipart/form-data',
      }

I want to test that route and my payload is this:

const FD = new FormData();
    FD.append('field1', 'value');
    FD.append('field2', 'value');

The hapi inject method looks like this:

    const res = await server.inject({
      method,
      url,
      headers: {
        ...
        'Content-Type': 'multipart/form-data; boundary=--SEPARATION--',
      },
      payload: FD,
    });

I am getting

Invalid multipart payload format

I tried to set a stream using a Steam object too but it doesn't work. Also I tried to send a File object.

At this point I just want to send something to the route that will not result in an error. It's not necessary to be a FormData. Anything that will be accepted by the route is fine as long as I can add some custom fields to test it further.

Thanks in advance.

1 Answers

As far as I know, FormData doesn’t exist in node.js, so I assume you’re using the form-data module?

In that case, you need to ask form-data for the buffer and headers separately, like this:

const FormData = require('form-data');

const FD = new FormData();
FD.append('field1', 'value');
FD.append('field2', 'value');

const response = await server.inject({
    method,
    url,
    headers: {
        <your other headers>
        ...FD.getHeaders(),
    },
    payload: FD.getBuffer(),
});

If you want to test sending files, you also need to provide the filename property to append(…) for the binary data to be decoded correctly by the server:

const fileContent = <any Buffer>;
FD.append('form_file_property', fileContent, {filename: 'a testfile'});
Related