Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: PUT binary data from ArrayBuffer to the server

Ok, so I try to read a PDF file like this:

reader.readAsArrayBuffer(file);

and then try to send it to the server using $http like this:

$http.put(url, data, {headers: {'Content-Type': 'application/pdf'}});

So, just read & send the binary to the server in raw form. According to some resources I found, passing an ArrayBuffer to XHR should work, but passing it as data to $http just results in a request body like this: {} and Content-Length=2

Reading the file readAsBinaryString() results in a corrupted file (and is apparently deprecated for that very reason)

The use case seems so trivial to me, am I missing something?

Chrome 36, Angular 1.2.20

like image 665
joerx Avatar asked Aug 06 '14 05:08

joerx


2 Answers

You have to use reader.readAsArrayBuffer(file); then in the onload callback create an ArrayBufferView from the result:

new Uint8Array(reader.result)

pass that data to $http and overwrite the transformRequest property so angularjs doesn't encode your array into json:

reader.onload = function() {
    $http({
        method: 'PUT', 
        headers: {'Content-Type': 'application/pdf'}, 
        data: new Uint8Array(reader.result), 
        transformRequest: []
    })
};
reader.readAsArrayBuffer(file);
like image 171
timbz Avatar answered Oct 19 '22 01:10

timbz


Is it because you are just handing the $http method the array buffer instead of writing that buffer into a byte array? If so what you are posting to the server is probably just the arraybuffer object.

Check this post on how to write ArrayBuffer to byte array: How do I read binary data to a byte array in Javascript?

like image 1
Kristian Barrett Avatar answered Oct 18 '22 23:10

Kristian Barrett