Reputation: 249
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?
Upvotes: 0
Views: 788
Reputation: 215
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
}
Upvotes: 2