简体   繁体   English

如何在 hapi.js 中处理 arrayBuffer?

[英]How to handle arrayBuffer in hapi.js?

I need to upload arrayBuffer to server and save it to file.我需要将 arrayBuffer 上传到服务器并将其保存到文件中。 I am using axios on the client side, and hapi js as a sever.我在客户端使用 axios,hapi js 作为服务器。 I do not know how to extract data from request in hapi handler.我不知道如何从 hapi 处理程序中的请求中提取数据。

Axios code axios 代码

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

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

Hapi router and handler 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});
        })
    };

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?有没有人可以帮助我举例说明如何在 hapi 中处理数组缓冲区?

To make payload an instance of a readable stream, you need set parse as false, thus returning the stream unmodified.要使有效负载成为可读流的实例,您需要将 parse 设置为 false,从而返回未修改的流。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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