简体   繁体   中英

How to handle arrayBuffer in hapi.js?

I need to upload arrayBuffer to server and save it to file. I am using axios on the client side, and hapi js as a sever. I do not know how to extract data from request in hapi handler.

Axios code

const config = {
                    data: image //image- arraybuffer object (UInt8)
                };

 axios.post(HOST_URL + '/upload', config)

Hapi router and handler

const fs = require('fs');
var Readable = require('stream').Readable;
var _ = require('underscore');
...
 server.route({
        path: '/upload',
        method: 'POST',
        options: {
            payload: {
                output: 'stream',
                maxBytes: 50 * 1024 * 1024
            }
        },
        handler: async (req, h) => {
            const { payload } = req;
            const response =  handleFileUpload(payload,h);
            return response;
        }
    });
    const handleFileUpload = (p,h) => {
        return new Promise((resolve, reject) => {
            var imagestream = new Readable;
            imagestream.push(new Buffer(_.values(p)));//problem here!!!
            imagestream.push(null);
            let filepath = 'D:\\tmp\\'+"image.nii"
            imagestream.pipe(fs.createWriteStream(filepath));
            return h.response({"ok":true});
        })
    };

The problem is that the data are not "extracted" from payload and promise is rejected when tries to create Buffer. Does anyone can help me with example how to handle arraybuffers in hapi?

To make payload an instance of a readable stream, you need set parse as false, thus returning the stream unmodified.

payload: {
    output: 'stream',
    maxBytes: 50 * 1024 * 1024,
    parse: false
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM