0

I try to upload a image to my Hapijs Server via stream and send(pipe) the data to another Hapijs instance.

So I have this post Route, which should receive a stream and forward it:

 this.server.route({
            method: "POST",
            path: RouteManager.Routes.SearchRoute.User.Icon.post,
            config: {
                payload: {
                    output: 'stream',
                    parse: true,
                    allow: 'multipart/form-data',
                    maxBytes: 4194304 //4MB
                },
                handler: (request, reply) => {
                    const data = request.payload.image;
                    const req = require("request").post("myOtherServer.com" + "/upload",
                    {
                      formData: {
                        image: data
                    }
                }, (err, httpResp, body) => {
                    cb(err, JSON.parse(body));
                });
                }
            }
        })

My route on the other Server looks like this:

 this.hapi.route({
            method: 'POST',
            path: Routes.index.child.upload.post,
            config: {
                payload: {
                    output: 'stream',
                    parse: true,
                    allow: 'multipart/form-data',
                    maxBytes: 4194304 //4MB
                }
                }
            },
            handler: (request, reply) => {       
                    this.workWithStream(request, reply);
            }
        });

When i run the code i get always this response:

{
  "statusCode": 400,
  "error": "Bad Request",
  "message": "Invalid multipart payload format"
}

How is it possible to forwarding a stream to another hapijs server(without to save a temporary file)?

Thanks

laren0815
  • 265
  • 1
  • 5
  • 22

1 Answers1

0

This is the sort of thing that the plugin h2o2 can be used for.

Register it like you would any other plugin:

server.register({
    register: require('h2o2')
}, function (err) {

    if (err) {
        console.log('Failed to load h2o2');
    }

    server.start(function (err) {

        console.log('Server started at: ' + server.info.uri);
    });
});

Then the following route will get you started with forwarding a stream to your other server:

{
    method: 'POST',
    path: '/upload',
    config: {
        payload: {
            output: 'stream',
            parse: false,
            allow: 'multipart/form-data',
            maxBytes: 4194304
        },
        auth: false
    },
    handler: {
        proxy: {
            host: 'your.remote.server',
            port: 'your-remote-port',
            protocol: 'http'
        }
    }
}

For proxying to work, parse has to be set to false on the proxy server, but can be set to true on the server that's actually processing your file.

For this example to work, the paths on both servers must be the same.

Cuthbert
  • 2,908
  • 5
  • 33
  • 60