正确的方法是不要设置Content-Type
头。
var formData = new FormData();
formData.append('blobImage', blob, 'imagem' + (new Date()).getTime());
return $http({
method: 'POST',
url: api + '/url',
data: formData,
})
其他头部(例如Authorization
)也可以。这是一个示例:
import { http } from '@angular/common/http'
function sendPostData(form: FormData) {
const url = `https://post-url-example.com/submit`;
const options = {
headers: new HttpHeaders({
Authorization: `Bearer auth-token`
})
};
return http.post(url, form, options);
}
进一步添加Pablo的答案。
当HTTP请求正文具有FormData
类型时,Angular将推迟Content-Type
标头分配给浏览器。detectContentTypeHeader()
将在FormData
请求正文上返回null
,并且Angular不会设置请求标头。
这是在@angular/commons/http/src/xhr.ts
模块中的。
if (!req.headers.has('Content-Type')) {
const detectedType = req.detectContentTypeHeader();
if (detectedType !== null) {
xhr.setRequestHeader('Content-Type', detectedType);
}
}
基于请求体的内容类型检测:
detectContentTypeHeader(): string|null {
if (this.body === null) {
return null;
}
if (isFormData(this.body)) {
return null;
}
if (isBlob(this.body)) {
return this.body.type || null;
}
if (isArrayBuffer(this.body)) {
return null;
}
if (typeof this.body === 'string') {
return 'text/plain';
}
if (this.body instanceof HttpParams) {
return 'application/x-www-form-urlencoded;charset=UTF-8';
}
if (typeof this.body === 'object' || typeof this.body === 'number' ||
Array.isArray(this.body)) {
return 'application/json';
}
return null;
}
源代码:
'multipart/form-data
的闭合引号。 - guest271314