Angular 4到Django REST图像上传

时间:2017-09-30 22:47:15

标签: django angular django-models django-rest-framework image-uploading

我有一个带有models.ImageField()的django REST API,我可以从django本身上传照片,我的问题是当我试图从角度进行。

  

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 个答案:

答案 0 :(得分:1)

https://github.com/Hipo/drf-extra-fields 好神的图书馆:D!

<button (click)="addKid()"> Add kid </button

numberOfKids: number = 0;

addKid() {
 this.numberOfKids++;
 let input = this.renderer.createElement('input');
 this.renderer.appendChild(form, input);
 this.renderer.setProperty(input, 'formControlName', this.numberOfKids); 

 this.details.addControl(this.numberOfKids, new FormControl(''));
}

photo =来自models.py的Imagefield,照片不需要在字段上,但我保留它以便通过DRF快速创建!