[英]How to change content type in django restframework api from json to multipart/form-data or form data
[英]How to post multipart/form-data from angular to Django REST API
我正在使用Django REST API和Angular 6作為前端。
我已經在Profile模型中定義了一個ImageField來接受File輸入。
在有角度的應用程序中,我從Base64圖像數據生成File對象,並以Header作為Content-Type發送到端點:'multipart / form-data'
發送的數據是
其中first_name
和profile.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.