[英]Angular 4 to Django REST image upload
我有一個帶有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()
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的Imagefield,照片不需要在字段上,但我保留它以便通過DRF快速創建!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.