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!