离子2上传图片到django休息 [英] ionic 2 upload image to django rest

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

问题描述

我正在尝试通过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请求错误。

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地址服务我的Django项目192.168.22.4):

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:

and 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')

离子离子一边,你必须提交实际图像而不是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);
      });  

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

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