如何在hapi.js中处理arrayBuffer?

时间:2019-04-10 00:32:14

标签: javascript node.js hapijs

我需要将arrayBuffer上传到服务器并将其保存到文件。我在客户端使用axios,将hapi js作为服务器。我不知道如何在hapi处理程序中从请求中提取数据。

Axios代码

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

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

Hapi路由器和处理程序

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});
        })
    };

问题在于,数据没有从有效负载中“提取”,并且在尝试创建Buffer时拒绝了promise。有谁能帮助我举例说明如何在hapi中处理数组缓冲区?

1 个答案:

答案 0 :(得分:0)

要使有效负载成为可读流的实例,您需要将parse设置为false,从而返回未经修改的流。

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