我正在使用angular上传图像,如下面的代码所示。
文件数据是从this.formGroup.value中检索的,但是问题是当将此文件数据传递给formData时,发现formData仍然为空,因此无法通过http请求发送。我不知道如何解决这个问题。任何想法或其他方式?
const formData: any = new FormData();
formData.append("avatar", this.formGroup.value);
console.log(formData);
this.http.post(environment.baseUrl + '/api/users/picture',formData);
整个代码如下所示。
<form action="uploadUrl" [formGroup]="formGroup" method="post" enctype="multipart/form-data" (ngSubmit)="onSubmit()">
<input type="file" name="avatar" />
<button type="submit" [disabled]="formGroup.invalid || formGroup.prestine">Submit</button>
onSubmit(){
console.log('onSubmit',this.formGroup.value);
const formData: any = new FormData();
formData.append("avatar", this.formGroup.value);
console.log(formData); // the formData is empty
this.http.post(environment.baseUrl + '/api/users/picture',formData);
.subscribe( res => {
console.log(res);
}, error => {
console.log('changePicture error',error);
});
}
答案 0 :(得分:0)
我个人这样做:
模板:
<input formControlName="picture"
(change)="onFileChange($event)"
class="form-control"
type="file"
id="picture"
name="picture">
组件:
onFileChange(event) {
const file = event.target.files[0];
this.formData.append('avatar', file, file.name);
this.http.post(environment.baseUrl + '/api/users/picture',this.formData);
.subscribe( res => {
console.log(res);
}, error => {
console.log('changePicture error',error);
});
}
我将标头添加到我的http请求中以允许表单数据:
headersConfig['enctype'] = 'multipart/form-data';
答案 1 :(得分:0)
我有一个相同的触发器,但是我运行它:
//--------------
formData.append('file', fileInput.files[0]);
const options = {
method: 'POST',
body: formData,
};
fetch('your-upload-url', options);