Search code examples
angularjscordovaimgur

Sending a "binary file" with AngularJS


I'm trying to upload a "binary file" from my cordova app into the imgur.com REST API using AngularJS.

But I'm not sure how I should format my request and what the "binary file" format is. From what I understand, a binary file is any thing that is not plain-text.

This is how I get file data from the local file system. It returns a blob instance. This part works fine.

var request = {
  'url': 'file:///my/path/tmp/cdv_photo_025.png',
  'options': {
    'responseType': 'blob' // also tried 'arraybuffer', no diff.
  }
}
var handler = function(response) {
  window.myBlobData = response.data;
  // handles the response
}
$http.get(request.url, request.options).then(handler);

Then later, I am using this to upload the blob to imgur, but this not working. I get a 400 (Bad Request). I am assuming the content-type, the disabling of the automatic encoding AngularJS does with transformRequest, and of course the binary data:

var request = {
  'url': 'https://api.imgur.com/3/upload',
  'options': {
    'headers': {
      'Authorization': 'Client-ID ***********',
      'Content-Type': 'application/octet-stream',
    },
    'transformRequest': []
  },
  'data': {
    'image': window.myBlobData, // a binary file
    'type': 'image/png'
  }
}
var handler = function(response) {
  // handles the response
}
$http.post(request.url, request.data, request.options).then(handler);

Solution

  • For an image upload request with Imgur's API, you can't simply include the Client-ID in the header. If you were instead requesting public read-only information, then that would've been adequate.

    If you haven't already, refer to the section on authorization in the Imgur API documentation.

    Basically, you'll need to obtain an access token for the user for which you'll be uploading images on behalf of. As suggested by the documentation, you'll want to redirect or open a pop-up window to the below URL.

    https://api.imgur.com/oauth2/authorize?client_id=YOUR_CLIENT_ID&response_type=access_token
    

    Then, once you've obtained the access token, ensure your upload requests use it:

    'Authorization': 'Bearer access_token'
    

    Furthermore, simply use your blob data as the argument for the request (i.e. don't wrap it with the image and type properties).