Django休息和Angular 5上传图片

时间:2018-04-25 19:34:41

标签: django angular django-rest-framework

这里抓取表单的图像,我调用服务来传递数据

handleFileInput(file: FileList) {
    this.fileToUpload = file.item(0);
  }
  
  CreateDetailProduct(){
    let form = this.FormDetailProductCreate.value;
    let detailproduct = new Detailproduct(); 

    detailproduct.Id_Product = form.Id_Product.id;
    detailproduct.Id_TypeProduct = form.Id_TypeProduct.id;
    detailproduct.Id_Provider = form.Id_Provider.id;
    detailproduct.TotalPrice = form.TotalPrice;
    detailproduct.Quantity = form.Quantity;
    
    detailproduct.Image = this.fileToUpload;


      this.servicedetailproduct.postDetailProduct(detailproduct).subscribe();

 
  }
 <div class="button-row"> 
        <button matSuffix mat-mini-fab color="primary" (click)="imgFileInput.click()">
          <mat-icon>attachment</mat-icon>
        </button> 
        <input  formControlName="Image" hidden type="file" #imgFileInput accept="image/*" (change)="handleFileInput($event.target.files)"/> 
        <img class="imagesize" [src]="imagesUrl" alt="">
      </div>
      
      

from django.db import models
from Product.models import ProductModel
from TipoProducto.models import TipoProductoModel
from Proveedor.models import ProveedorModel
from LoteProducto.models import LoteProductoModel


class ProductDetailModel(models.Model):
    Id_Product = models.ForeignKey(ProductModel, null =False, blank=False, on_delete=models.CASCADE)
    Id_TypeProduct = models.ForeignKey(TipoProductoModel, null =False, blank=False, on_delete=models.CASCADE)
    Id_Lote = models.ForeignKey(LoteProductoModel, null =False, blank=False, on_delete=models.CASCADE)
    Id_Provider = models.ForeignKey(ProveedorModel, null =False, blank=False, on_delete=models.CASCADE)
    TotalPrice = models.FloatField()

    Quantity = models.IntegerField()
    Image = models.ImageField(upload_to="ProductDetail/images/", null=True, blank=True)

发送图片时出现此错误

  

{Image:[“提交的数据不是文件。检查表单上的编码类型。”]}

如何将角度5中的图像加载到django,或者我做错了什么

1 个答案:

答案 0 :(得分:1)

在你的post方法中,你必须做这样的事情:

postDetailProduct(detailproduct) {
    let formData: FormData = new FormData();

    if (detailproduct) {
        for(let key in detailproduct){
            formData.append(key, detailproduct[key]);
        }
    }

    formData.append('thumbnail', detailproduct.Image, detailproduct.Image.name);

    return this._http.post(url, formData)
        .pipe(
            map(res => res.json())
        );
 }

Pd:请告诉我此解决方案是否适合您。