我有一个表单中的文件上传。我还需要使用此上传的文件和其他一些表单字段创建对后端的发布请求。
下面是我的代码:
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);
});
}
除上传的文件外,每个字段值都会发送到后端。如何将上传的文件与表单字段一起发送到后端?
如果需要任何其他信息,请告诉我。
您正在尝试简单地传递文件数据
'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 中的文件上传? https://stackoverflow.com/questions/40214772/file-upload-in-angular
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)