1

Ich habe eine Django REST API mit einem models.ImageField(), ich kann Fotos von Django selbst gut hochladen, mein Problem ist, wenn ich versuche, es aus Winkel zu tun.Angular 4 to Django REST Bild hochladen

.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]); 
    } 

Fehler ist this.imageSrc keine Datei ist, wie soll ich diese Vergangenheit bekommen? Welche Daten muss ich an ein ImageField senden()

Antwort

1

https://github.com/Hipo/drf-extra-fields Gut gottähnliche Bibliothek: 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 

Foto = Imagefield von models.py, benötigen Foto doesnt auf den Feldern sein, aber ich halte es für eine schnelle Erstellung durch DRF!