6

I want to upload a binary file (images) to an api which accepts application/octet-stream. Unfortunately it seems angular wants to transform my request, which does not work obviously and results in TypeError: key.charAt is not a function

My request looks like this:

var f = document.getElementById('file_picker').files[0],
r = new FileReader();
r.onloadend = function(e){
    var fileData = e.target.result;
    $http({
        url: '.../upload/' + id,
        method: 'PUT', 
        headers: {'Authorization': 'Bearer asdf',
        'Content-Type': 'application/octet-stream'}, 
        data: new Uint8Array(fileData), 
        transformRequest: []
    })
})
r.readAsArrayBuffer(f);

This is my request via curl which works:

curl -i -X PUT -H "Authorization: Bearer asdf" -H "Content-Type: application/octet-stream" --data-binary @jpg.jpg https://.../upload/123

Any ideas? Thanks.

2 Answers 2

2

try this:

            var fd = new FormData();
            fd.append("file", fileObj);

            $http({
                method: "POST",
                params: { 'forcecache': new Date().getTime() },
                url: <yoururl>,
                headers: {
                    "Content-Type": undefined
                },
                transformRequest: angular.identity,
                data: fd
            });

This is a working example on one of our projects. See http://www.uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs/ for more details

Sign up to request clarification or add additional context in comments.

2 Comments

Does not work for me like this, because the Content I receive within the API is probably wrong. It's content length is 15. Not very big for an image.
Update: The content of the request is: "[object Object]". Thats why the content length is 15.
1

Working solution:

var file = document.getElementById('file_picker').files[0],
reader = new FileReader();
reader.onload = function() {
    var f = new Uint8Array(reader.result);
    $http({
        url: '...upload/,
        method: 'PUT',
        headers: {'Authorization': 'Bearer asdf',
                'Content-Type' : undefined},
        data: f, 
        transformRequest: [] 
      });
    };
reader.readAsArrayBuffer(file);

The problem is, we have a Data Mapping Interceptor configured, which converts all post and put requests to json. Ouch.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.