1

我有一个django REST API与models.ImageField(),我可以上传照片就好,从Django本身,我的问题是当我试图从角度做它。角4到Django REST图像上传

的.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> 

component.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()

回答

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 

照片=的ImageField从models.py,照片犯规必须在字段,但我把它快速创建通过DRF!