1

장고 REST API를 models.ImageField()와 함께 사용하면 장고 자체에서 사진을 업로드 할 수 있습니다. 제 문제는 각도에서 시도하는 것입니다.Angular 4 to Django REST image 업로드

.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 

사진 = models.py의 이미지 필드, 사진이 필드에 있어야 할 필요는 없지만 DRF를 통해 빠르게 만들 수 있습니다!