Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

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

share|improve this question

2 Answers 2

up vote 10 down vote accepted

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);
share|improve this answer
    
Is it just standard behaviour for AngularJS to encode everything into json? I don't see why one would encode byte arrays as json data. – Kristian Barrett Aug 6 '14 at 13:13
    
@tbaetz: I was banging my head for almost two days with it... Thanks for that answer. – jjczopek Mar 28 at 10:07
    
@tbaetz: Half a day of work, and finally saved by your solution. You're great, man. – blas3nik Sep 24 at 12:13

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?

share|improve this answer
    
Almost, but without overriding transformRequest it still won't work. – joerx Aug 6 '14 at 11:53

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.