javascript - 使用 Angular 通过 post 将文件上传/发送到 django REST
问题描述
我在这里看到多个线程,我无法修复它。
我有一个后端 django-REST,它使用 django-versatileimagefield 来处理图像而不是图像域。我使用 Postman 测试后端并且工作正常。但是当我通过 Angular POST 发送请求时,我得到了下一个错误:
"The submitted data was not a file. Check the encoding type on the form."
在Angular APP中,我从base64创建文件,然后生成一个blob,最后我创建图像并尝试使用多种方式上传,最后一种方式是下一个:
<button (click)="guardarCambios()" ....>
guardarCambios(){
let base64 = this.croppedImage // this value get a base64 image from another part of my app
let imageName = 'name.png'
let imageBlob = new Blob([base64], {type: 'image/png'});
let imageFile = new File([imageBlob], imageName, { type: 'image/png' })
let me = this;
let reader = new FileReader();
reader.readAsDataURL(imageFile);
reader.onload = function () {
console.log(reader.result);
me.ImageBaseData=reader.result;
okok()
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
let okok = () => {
if(this.ImageBaseData != undefined){
this.form.get('image').setValue({
filename: imageFile.name,
filetype: imageFile.type,
value: this.ImageBaseData.toString().split(',')[1]
})
const enviar = this.form.value;
this.subirfile(enviar)
}
}
}
subirfile(enviar){
this.api.upImagen(enviar).subscribe(
(item2:any) => {
console.log(item2)
});
}
upImagen(id, imagen:any){
let httpOptions = {
headers: new HttpHeaders({
'Authorization': 'JWT ' + localStorage.getItem('token')
})
};
return this.http.post(this.apiRoot.concat(`v2imagen/`), imagen, httpOptions);
}
任何人都可以帮助我吗?提前致谢