Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return ArrayBuffer from $http request in Node.js?

I sent a $http.post request from Angular.js to Node.js in order to get an ArrayBuffer as following:

$http.post('/api/scholarships/load/uploaded-files', Global.user, {responseType:'arraybuffer'}).success(function(ab){
    console.log(ab); // Return ArrayBuffer {}
});

Then, in Node.js, I retrieved uploaded files data and transform a Buffer object to ArrayBuffer object:

exports.loadUploadedFiles = function(req, res) {
    db.UserFile.findAll().success(function(files) {
        var buffer = files[0].dataValues.data; // Get buffer
        var arrayBuffer = new ArrayBuffer(buffer.length); // Start transforming Buffer to ArrayBuffer
        var views = new Uint8Array(arrayBuffer);
        for(var i = 0; i < buffer.length; ++i) {
            views[i] = buffer[i];
        }
        res.type('arraybuffer');
        res.send(arrayBuffer); // Send the ArrayBuffer object back to Angular.js
    }).error(function(err) {
        console.log(err);
        res.sendStatus(500);
    });
};

When I tried to print the response from above $http.post, I always got ArrayBuffer{}. What did I do wrong? Any help would be appreciated.

like image 650
lvarayut Avatar asked Jan 01 '15 05:01

lvarayut


1 Answers

There is no need to create an ArrayBuffer on the server side. In fact just returning the Buffer in node.js should be fine. ArrayBuffer is a concept on the client/browser side to interpret the data coming from the server as an ArrayBuffer. The reason you are getting "ArrayBuffer{}" is probably because node.js is toString()'ing the ArrayBuffer on res.send() because it doesn't understand the object. So try this

exports.loadUploadedFiles = function(req, res) {
    db.UserFile.findAll().success(function(files) {
        var buffer = files[0].dataValues.data; // Get buffer
        res.send(buffer);
    }).error(function(err) {
        console.log(err);
        res.sendStatus(500);
    });
};
like image 159
ekcr1 Avatar answered Oct 04 '22 16:10

ekcr1