Search code examples
node.jshapi.js

Uploading multiple files with HapiJS


I am trying to upload multiple files in a single request to a Hapi JS server. So far I'm not successful. Here is the raw request (taken from w3org to make the process as simple as possible).

Content-Type: multipart/form-data; boundary=AaB03x

--AaB03x
Content-Disposition: form-data; name="submit-name"

Larry
--AaB03x
Content-Disposition: form-data; name="files"
Content-Type: multipart/mixed; boundary=BbC04y

--BbC04y
Content-Disposition: file; filename="file1.txt"
Content-Type: text/plain

... contents of file1.txt ...
--BbC04y
Content-Disposition: file; filename="file2.gif"
Content-Type: image/gif
Content-Transfer-Encoding: binary

...contents of file2.gif...
--BbC04y--
--AaB03x--

This is the handler configuration at the Hapi side:

path: '/1.1/playbacks/new',
method: 'POST',
config: {
    payload: {
        maxBytes: 209715200,
        output: 'file',
        parse: true
    },
    auth: 'token'
}

When I debug request.payload, I only see two fields, "files" and "submit-name" with the files field holding all the content between --BbC04y boundaries, which is "--BbC04y\r\nContent-Disposition: file; filename="file1.txt"\r\nContent-Type: text/plain\r\n...--BbC04y--"

So what's the proper way to upload multiple files to Hapi JS?


Solution

  • The sample taken from w3org is wrong! This is how the request should be:

    ------WebKitFormBoundaryfXvbZd3ZABBHzmdC
    Content-Disposition: form-data; name="name"
    
    123456
    ------WebKitFormBoundaryfXvbZd3ZABBHzmdC
    Content-Disposition: form-data; name="last"
    
    789000
    ------WebKitFormBoundaryfXvbZd3ZABBHzmdC
    Content-Disposition: form-data; name="upload1"; filename="test1"
    Content-Type: application/octet-stream
    
    file 1
    
    ------WebKitFormBoundaryfXvbZd3ZABBHzmdC
    Content-Disposition: form-data; name="upload2"; filename="test2"
    Content-Type: application/octet-stream
    
    file 2
    
    ------WebKitFormBoundaryfXvbZd3ZABBHzmdC--
    

    Note that there is no need for different boundary values. They're all the same.

    Got it with the help of wonderful tool http://requestb.in