【问题标题】:Angular $http post with data:image/png;base64 field带有数据的 Angular $http 帖子:image/png;base64 字段
【发布时间】:2016-03-30 13:24:31
【问题描述】:

我已经用 Django Rest Framework 作为后端构建了一个 Angular 应用程序。

在用户个人资料编辑页面中,它包含使用ngImgCrop 进行的图片裁剪。然后我得到了裁剪后的图像结果为 data:image/png;base64.

但是当我在控制器中调用 $http 补丁来更新服务器端的图片时,我总是得到 400 Bad Request "提交的数据不是文件。检查表单上的编码类型."。我认为它来自 data:image/png;base64。

这是我的角度代码。有谁知道如何解决这个问题?还是我做错了什么?

$http({
  method : 'PATCH',
  url : ,
  data : {
    profile_picture: $scope.croppedProfilePicture
  }
}).then(function () {
  ...
});

我也尝试为此请求添加一些标头,但仍然没有成功。

headers : {'Content-Type': undefined }

【问题讨论】:

  • 你能先发布图片吗?另外,服务器抛出的具体错误是什么?
  • @user2954587 感谢您的帮助。 POST 和 PATCH 都出现同样的错误。
  • 能否请您发布错误信息?
  • @user2954587 错误 400 错误请求“提交的数据不是文件。请检查表单上的编码类型”。
  • 我只是尝试将请求发送到 content-type = form-data 标头并且它的工作。也许这个问题发生在后端(Django Rest Framework)。但我仍然不知道如何以 Angular 的方式将请求作为表单数据提交。

标签: angularjs rest django-rest-framework


【解决方案1】:

这是一个示例 fileUploadService 和一个调用它的控制器

services.service('fileUploadService', ['$http', function ($http) {
  this.uploadFileToUrl = function(file, uploadUrl, params){
    var fd = new FormData();
    fd.append('file', file);
    promise = $http.post(uploadUrl, fd, {
      transformRequest: angular.identity,
      headers: {'Content-Type': undefined},
      params: params
    });

    return promise;
  }
}]);

在您的控制器中,您可以像这样使用fileUploadService

  $scope.sendToServer = function() {
    var uploadUrl = '/myUrl/';
    fileUploadService.uploadFileToUrl(
      $scope.croppedImage, uploadUrl, {}).then(function(resp) {
        // handle response
    })
  };

【讨论】:

  • 谢谢举个例子,让我试试。
【解决方案2】:

您还必须将图像转换为 Base64 才能将图像发布到 Django-Rest 框架。

【讨论】:

    猜你喜欢
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 2014-03-07
    相关资源
    最近更新 更多