【问题标题】:Upload image using ionic, angular, and django+restframework使用 ionic、angular 和 django+rest 框架上传图片
【发布时间】:2015-12-23 12:52:02
【问题描述】:

我正在开发一个应用程序,我希望能够将照片上传到后端(restframework + django)。

对于后端,我关注了tutorial。 当我使用:

curl --verbose --header "Authorization: token {TOKEN}" --header "Accept: application/json; indent=4" --request POST --form photo=@/home/.../uyuni.jpg {DOMAIN}/api/users/1/photo/

这很好用,文件真的被创建了,之后我可以使用 ng-src 检索它。

然后,我想连接前端来上传照片。

在这里,我尝试了很多来自论坛或 tutos 的想法,例如 one

我有两个不同的问题。

  • 如果我复制最后一个 tuto,我最终会收到 400 Bad Request: 错误分析 XML : aucun élément trouvé 安置 : moz-nullprincipal:{1b4583fc...} Numéro de ligne 1, Colonne 1 : 我不知道它是来自后端还是 Mozilla。我阅读了有关 CORS 问题的信息,但这应该不是问题,因为我使用了离子代理。

  • 如果我使用 cordova-plugin-camera 进行连接,我会返回一个 URL (file:///home/.../example.jpg),我不知道如何将其连接到 FormData用于 POST 到后端:

    var updateUserPhoto = function (userId, photoURI) {
    if (!photoURI) {return}
    var fd = new FormData();
    fd.append('photo', photoURI);
    return $http.post(API_URL + "users/"+userId+"/photo/", fd, {
        transformRequest: angular.identity,
        headers: {AUTHORIZATION: "Token "+window.localStorage['apiToken'], 'CONTENT-TYPE': undefined}
        });
    };

我试图在 fd 中附加一个对象,例如 {path: photoURI, name: 'blablabla'} 在这个问题中,我最终遇到了一个 Django 错误:

AttributeError at /api/users/1/photo/ 'str' object has no attribute 'name'

我可能没那么远,所以我宁愿不使用外部sn-ps。

【问题讨论】:

    标签: javascript python angularjs django


    【解决方案1】:

    我有非常相似的问题,然后是一些。这个来自 Ionic 市场的 Media plugin 通过提供 base64 数据和 uri 供我使用解决了这个问题。

    【讨论】:

      【解决方案2】:

      我终于解决了我的问题。哎哟!

      我在后端使用了这个:

      import base64
      
      from django.db.models import ImageField
      from django.db.models.fields.files import ImageFieldFile
      from django.core.files.uploadedfile import InMemoryUploadedFile
      
      
      def upload_to(instance, filename):
          return 'profiles/' + filename
      
      
      def wrap(content):
          class File(InMemoryUploadedFile):
              def read(self):
                  return base64.b64decode(super().read())
          return File(content.file, content.field_name, content.name, content.content_type, content.size, content.charset)
      
      
      class Base64ImageFieldFile(ImageFieldFile):
          def save(self, name, content, save=True):
              super().save(name, wrap(content), save=True)
      
      
      class Base64ImageField(ImageField):
          attr_class = Base64ImageFieldFile
      

      在前端:

      配置我的资源:

      var userActions = getActions(User);
      var updatePhotoHeader = angular.copy(auth_header);
      updatePhotoHeader['CONTENT-TYPE'] = undefined;
      
      userActions['updatePhoto'] = {
          method: "POST",
          url: API_URL + "users/:userId/photo/",
          params: {userId: "@userId"},
          headers: updatePhotoHeader,
          transformRequest: function (data) {
              if (!data) {return}
              var fd = new FormData();
              fd.append('photo', new Blob([data.photo], {type: 'image\/jpeg'}));
              return fd
          }
      };
      

      使用此相机选项(来自 cordova 插件):

          var cameraOptions = {
          quality: 75,
          destinationType: 0,
          targetWidth: 750,
          targetHeight: 500,
          saveToPhotoAlbum: false,
          cameraDirection: 1,
          allowEdit: true,
          encodingType: 0    // 0=JPG 1=PNG
      };
      

      PS:这个解决方案可能不是最好的。还是希望能找到更好的。但我现在会继续这样做。

      【讨论】:

        猜你喜欢
        • 2019-07-01
        • 2014-03-15
        • 2017-07-26
        • 1970-01-01
        • 2018-10-06
        • 2016-05-02
        • 1970-01-01
        • 1970-01-01
        • 2018-08-17
        相关资源
        最近更新 更多