【问题标题】:Angular 4 to Django REST image uploadAngular 4 到 Django REST 图像上传
【发布时间】:2018-03-12 11:23:20
【问题描述】:

我有一个带有 models.ImageField() 的 django REST API,我可以从 django 本身上传照片,我的问题是当我尝试从 angular 上传照片时。

.html

<div class="form-group">
 <label for="usr">Upload your new photo(Optional):</label> <input type="file"  accept=".jpg,.png,.jpeg" (change)="attachFile($event)">
 <br>
 <img src="{{imageSrc}}"   height="250" weight="250" alt="Image preview..." />
</div>

组件.ts

Update(form){
  let body = {
    house: 3,
    photourl: this.imageSrc
  }
  console.log(this.imageSrc)
  this.http.Post('http://127.0.0.1:8000/api/photos', body).subscribe( res => console.log(res))
  console.log(form)
}

attachFile(event) : void {
    var reader = new FileReader();
    let _self = this;

    reader.onload = function(e) {
      _self.imageSrc = reader.result;
    };
    reader.readAsDataURL(event.target.files[0]);
   }

错误是 this.imageSrc 不是文件,我应该如何解决这个问题?我需要将哪些数据发送到 ImageField()

【问题讨论】:

    标签: django angular django-models django-rest-framework image-uploading


    【解决方案1】:

    https://github.com/Hipo/drf-extra-fields 好神一样的图书馆:D!

    class HouseImSerializer(serializers.ModelSerializer):
        image = Base64ImageField(required=False)
    
        class Meta:
            model = tedbnbhouseimages
            fields = ('house', 'image', 'photo')
    
        def create(self, validated_data):
            house = validated_data['house']
            if not validated_data['photo']:
                photo = validated_data['image']
            else:
                photo = validated_data['photo']
            houseimage = tedbnbhouseimages(
                house = house,
                photo = photo,
            )
            houseimage.save()
            return houseimage
    

    photo = 来自 models.py 的图像字段,照片不需要在字段上,但我保留它以便通过 DRF 快速创建!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-06
      • 1970-01-01
      • 2019-09-01
      • 2018-08-17
      • 1970-01-01
      相关资源
      最近更新 更多