用 AngularJS 发送 "binary file"

Sending a "binary file" with AngularJS

我正在尝试使用 AngularJS 从我的 cordova 应用程序将 "binary file" 上传到 imgur.com REST API

但我不确定我应该如何格式化我的请求以及 "binary file" 格式是什么。据我了解,二进制文件是任何非纯文本的文件。

这是我从本地文件系统获取文件数据的方式。它 returns 一个 blob 实例。这部分工作正常。

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

后来,我用它来将 blob 上传到 imgur,但这不起作用。我收到 400(错误请求)。我假设内容类型,自动编码 AngularJS 的禁用与 transformRequest 相关,当然还有二进制数据:

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

对于使用 Imgur 的 API 的图片上传请求,您不能简单地在 header 中包含 Client-ID。如果您改为请求 public read-only 信息,那就足够了。

如果您还没有,请参阅 Imgur API 文档中的 section on authorization

基本上,您需要为您将代表其上传图片的用户获取访问令牌。根据文档的建议,您需要将 pop-up window 重定向或打开到下面的 URL.

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

然后,一旦您获得了访问令牌,请确保您的上传请求使用它:

'Authorization': 'Bearer access_token'

此外,只需使用您的 blob 数据作为请求的参数(即不要用 imagetype 属性包装它)。