Javascript 如何使用post发送二进制文件多部分/表单数据?
我尝试使用post方法和多部分/表单数据发送一个包含附加字段的二进制文件Javascript 如何使用post发送二进制文件多部分/表单数据?,javascript,angular,Javascript,Angular,我尝试使用post方法和多部分/表单数据发送一个包含附加字段的二进制文件 load() { const formData = new FormData(); formData.append('file', this.data.binary); formData.append('reasons', this.form.get('reasons').value); const headers = new HttpHeaders({ key: user
load() {
const formData = new FormData();
formData.append('file', this.data.binary);
formData.append('reasons', this.form.get('reasons').value);
const headers = new HttpHeaders({
key: userKey,
});
const options = { headers: headers };
this.http
.post(`/api/Controller`, formData, options)
.pipe(catchError(this.handleError))
.subscribe(
() => {
alert('Success');
},
(error) => {
alert(error.Message || 'Error');
},
);
}
其中此.data.binary
为:
try {
const input = event.target as HTMLInputElement;
const reader = new FileReader();
reader.onload = () => {
this.data.binary = reader.result;
};
reader.readAsArrayBuffer(input.files[0]);
} catch (e) {
alert(e);
}
在Chrome标题中,我在提交后看到以下数据:
FormData
file: [object ArrayBuffer]
reasons: text
如何正确地以二进制格式发送文件
我还有一个问题:
formData.append('file', new Blob(this.data.binary));
不要使用FileReader将其作为二进制文件读取。 只需使用FormData并直接附加它
const formData = new FormData()
formData.append('file', input.files[0])
此外,readAsBinaryString是一种不好的做法,在处理二进制文件时应该使用arrayBuffer
我还建议您执行类似于newformdata(formElement)
的操作,这样您就不必追加/设置所需的每个字段