ionic 2 将图像上传到 django rest [英] ionic 2 upload image to django rest

查看:14
本文介绍了ionic 2 将图像上传到 django rest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 Django Rest API 将图像从 Ionic 2 应用程序上传到 Django 驱动的网站.

I am trying to upload an image from Ionic 2 app to Django-powered website through Django Rest API.

API 正在通过 Postman 工作和测试,但我总是在 Ionic 中收到 HTTP 400 BAD Request 错误.

The API is working and tested through Postman but I always get HTTP 400 BAD Request error in Ionic.

这是我在 Ionic 中的代码:

Here is my code in Ionic:

openCamera(){
    var options = {
      sourceType: Camera.PictureSourceType.CAMERA,
      destinationType: Camera.DestinationType.DATA_URL
    };
    Camera.getPicture(options).then((imageData) => {
      this.imageName = imageData;
      this.imageURL = 'data:image/jpeg;base64,' + imageData;
    }, (err) => {
      this.showAlert(err);
    });
  } 

上传文件(我在本地 PC 上使用 IP 地址 192.168.22.4 为我的 Django 项目提供服务):

Upload file (I am serving my Django project on my local PC with IP address 192.168.22.4):

transferData(auth){
      let headers = new Headers();
      headers.append('Authorization', auth);

      let formData = new FormData();
      formData.append('image', this.imageURL, this.imageName);

      this.http.post("http://192.168.22.4/api-imageUpload", formData, {headers: headers}).subscribe(res => {
        let status = res['status'];
        if(status == 200){
          this.showAlert( "The image was successfully uploaded!");
        }else{
          this.showAlert("upload error");
        }

      }, (err) => {
        var message = "Error in uploading file " + err
        this.showAlert(message);
      });  
  }

在 Django 上,这是我的序列化程序:

On Django, here is my serializer:

class ImageDetailsSerializer(serializers.ModelSerializer):
    image = serializers.ImageField(max_length=None, use_url=True)
    class Meta:
        model = ImageDetails
        fields= ('image','status','category', 'user')   ####status, category has default value

和views.py:

class ImageDetailsViewSet(generics.ListCreateAPIView):
    queryset = ImageDetails.objects.all()
    serializer_class = ImageDetailsSerializer

我不确定我上传文件的代码是否正确.我正在尝试通过表单数据传递数据,因为表单在我的 API 中运行良好.这种方法正确吗?还有其他方法可以完成这项工作吗?

I am not sure if my code in uploading file is correct. I am trying to pass the data through Form data since the form works well in my API. Is this method correct? Are there any other methods to get this work?

注意:我曾尝试使用 Transfer Cordova 插件,但它不起作用.

Note: I have tried to use Transfer Cordova plugin but it is not working.

推荐答案

我终于解决了这个问题.HTTP 400 表示代码中某处存在语法错误,这是上传照片中使用的编码.移动数据使用 base64 编码.发送请求时,文件将被转换为 Unicode 字符串.

I finally solved the problem. The HTTP 400 indicates that there is a syntax error somewhere in the code and that is the encoding used in the uploaded photo. Mobile data uses base64 encoding. When sending requests, the file will then be converted to a Unicode string.

另一方面,Django-Rest 对图像使用普通编码,因此默认情况下,它不支持 base64 图像.但幸运的是,这个插件已经在 GitHub 提供.

On the other hand, Django-Rest uses normal encoding for images, thus by default, it cannot support base64 image. But luckily, this plugin is already available at GitHub.

您只需要安装插件并将其导入您的 serializers.py:

You just need to install the plugin and import it on your serializers.py:

from drf_extra_fields.fields import Base64ImageField
class ImageDetailsSerializer(serializers.ModelSerializer):
    image = Base64ImageField()  
    class Meta:
        model = ImageDetails
        fields= ('image','status','category', 'user')

在 Ionic 方面,您必须提交实际图像而不是 imageURL.就我而言,我只需将代码调整为:

On Ionic side, you have to submit the actual image not the imageURL. In my case I just have to tweak my code to:

transferData(auth){

      let headers = new Headers();
      headers.append('Authorization', auth);

      let formData = new FormData();
      formData.append('category', 1);
      formData.append('status', 'Y')
      formData.append('image', this.imageName); 

      this.http.post("http://192.168.22.4/api-imageUpload", formData, {headers: headers}).subscribe(res => {
        let status = res['status'];
        if(status == 201){
          var message = "The image was successfully uploaded!";
          this.showAlert(message);
        }else{
          var message = "upload error";
          this.showAlert(message);
        }

      }, (err) => {
        var message = "Error in uploading file " + err;
        this.showAlert(message);
      });  

这篇关于ionic 2 将图像上传到 django rest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆