作者:猪的快乐旅途_278 | 来源:互联网 | 2022-12-09 17:21
我在表格中上传了文件。我还需要创建发布请求以将此上传文件和其他一些表单字段作为后端。
下面是我的代码:
fileChange(event) {
const fileList: FileList = event.target.files;
if (fileList.length > 0) {
this.file = fileList[0];
this.form.get('file_upload').setValue(this.file);
}
}
onClick(){
const val = this.form.value;
const testData = {
'file_upload': this.file,
'id': val.id,
'name' : val.name,
'code': val.code,
};
this.http.post('https://url', testData,
.subscribe(
respOnse=> {
console.log(response);
});
}
除上载文件外,每个字段值都将发送到后端。我是否将上传的文件以及表单字段发送到后端?让我知道是否需要其他信息。
1> 小智..:
您正在尝试简单的传递文件数据
'file_upload': this.file,
这是错的
有很多方法上传文件,我喜欢使用FormData,例如:
let testData:FormData = new FormData();
testData.append('file_upload', this.file, this.file.name);
this.http.post('https://url', testData).subscribe(respOnse=> {
console.log(response);
});
此处有更多详细信息在Angular中上传文件?