簡體   English   中英

如何從角度發布多部分/表單數據到Django REST API

[英]How to post multipart/form-data from angular to Django REST API

我正在使用Django REST APIAngular 6作為前端。

我已經在Profile模型中定義了一個ImageField來接受File輸入。

在有角度的應用程序中,我從Base64圖像數據生成File對象,並以Header作為Content-Type發送到端點:'multipart / form-data'

發送的數據是

在此處輸入圖片說明

其中first_nameprofile.avatar是表單字段,而profile.avatar包含圖像文件。

但是在網絡選項卡中,為profile.avatar發送的參數為空字典。

在此處輸入圖片說明

如何將媒體文件作為表單數據從Angular發送到REST API?

編輯2:代碼

submit() {

    // call method that creates a blob from dataUri
    // imgSrc[0] contains base64 string
    const imageBlob = this.dataURItoBlob(this.imgSrc[0]);

    const extension = imageBlob['type'].split('/')[1];
    const imageName = 'file123' + '.' + extension;

    const imageFile = new File([imageBlob], imageName, { type: imageBlob['type'] });

    const fb = new FormData();
    fb.append('profile.avatar', imageFile, imageFile.name);

    this.account.updateProfile(fb, {headers: {'Content-Type': 'multipart/form-data'}}).subscribe(
        res => {
          console.log(res);
        },
        error => {
          console.log(error);
        }
    );
  }


  dataURItoBlob(dataURI: string) {
    // Split from , (comma)
    const b64Split = dataURI.split(',');

    const extension = 'png';

    // remove data:image/png;base64, from the base64 string
    dataURI = dataURI.replace(b64Split[0] + ',', '');

    const byteString = atob(dataURI);
    const arrayBuffer = new ArrayBuffer(byteString.length);
    const int8Array = new Uint8Array(arrayBuffer);

    for (let i = 0; i < byteString.length; i++) {
      int8Array[i] = byteString.charCodeAt(i);
    }
    const blob = new Blob([arrayBuffer], { type: 'image/png' });

    return blob;
  }

updateProfile方法正在使用PATCH方法發送數據。

我遇到了完全相同的問題。 在我的請求標頭中,我已經指定了內容類型。 刪除后,我就可以發送文本字段和文件。 對於您的帖子請求,您還必須使用formData,如下所示:

let formData = new FormData();
formData.append('textOrFileField', yourTextOrFile);

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM