我在表格中上传了文件。我还需要创建发布请求以将此上传文件和其他一些表单字段作为后端。
下面是我的代码:
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);
});
}
除上载文件外,每个字段值都将发送到后端。我是否将上传的文件以及表单字段发送到后端? 让我知道是否需要其他信息。
答案 0 :(得分:4)
您正在尝试的只是简单的传递文件数据
'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);
});
更多详细信息,请点击File Upload In Angular?
答案 1 :(得分:0)
假设您正在服务器上正确处理文件上传(通常是某些类型的npm软件包,如multer或busboy),
您需要在角度侧使用npm包来处理多部分表单数据。
ng-2-file-upload是其中一项工作。