How to put binary in API via AngularJs $ http

I want to load a binary file (images) into an api that accepts application/octet-stream. Unfortunately, it seems that angular wants to convert my query, which does not work explicitly and leads to TypeError: key.charAt is not a function

My query 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 through curl that works:

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

Any ideas? Thank.

+4
source share
2 answers

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 that we have a data mapping hook that converts all post and put messages to json. Uch.

0
source

try the following:

            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
            });

. . http://www.uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs/

0

Source: https://habr.com/ru/post/1665855/


All Articles