如何在 Angular 中获取或设置 multipart/form-data 的边界(boundary)?使用 FormData。

25

我有一个小应用程序,在其中必须从浏览器中发布表单数据到端点。

这是我的发布内容:

var formData = new FormData();
formData.append('blobImage', blob, 'imagem' + (new Date()).getTime());

return $http({
  method: 'POST',
  url: api + '/url',
  data: formData,
  headers: {'Content-Type': 'multipart/form-data'}
})

formData将边界添加到参数中,但我无法将其发送到标题中,该怎么做?


1
您缺少'multipart/form-data的闭合引号。 - guest271314
3个回答

58

好的,看起来头部的ContentType应该是未定义的,以便添加正确的边界


6

正确的方法是不要设置Content-Type头。

var formData = new FormData();
formData.append('blobImage', blob, 'imagem' + (new Date()).getTime());

return $http({
  method: 'POST',
  url: api + '/url',
  data: formData,
  // headers: {'Content-Type': 'multipart/form-data'}
})

其他头部(例如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模块中的。

  // Auto-detect the Content-Type header if one isn't present already.
  if (!req.headers.has('Content-Type')) {
    const detectedType = req.detectContentTypeHeader();
    // Sometimes Content-Type detection fails.
    if (detectedType !== null) {
      xhr.setRequestHeader('Content-Type', detectedType);
    }
  }

基于请求体的内容类型检测:

  detectContentTypeHeader(): string|null {
    // An empty body has no content type.
    if (this.body === null) {
      return null;
    }
    // FormData bodies rely on the browser's content type assignment.
    if (isFormData(this.body)) {
      return null;
    }
    // Blobs usually have their own content type. If it doesn't, then
    // no type can be inferred.
    if (isBlob(this.body)) {
      return this.body.type || null;
    }
    // Array buffers have unknown contents and thus no type can be inferred.
    if (isArrayBuffer(this.body)) {
      return null;
    }
    // Technically, strings could be a form of JSON data, but it's safe enough
    // to assume they're plain strings.
    if (typeof this.body === 'string') {
      return 'text/plain';
    }
    // `HttpUrlEncodedParams` has its own content-type.
    if (this.body instanceof HttpParams) {
      return 'application/x-www-form-urlencoded;charset=UTF-8';
    }
    // Arrays, objects, and numbers will be encoded as JSON.
    if (typeof this.body === 'object' || typeof this.body === 'number' ||
        Array.isArray(this.body)) {
      return 'application/json';
    }
    // No type could be inferred.
    return null;
  }

源代码:


4

如果还有其他人遇到类似的问题... 如果您正在提交FormDate,则浏览器应该为您设置内容类型。 为了使其工作,我只需将enctype标头设置为multipart / form-data

const formData = new FormData();
formData.append('file', file);
let headers = new HttpHeaders();
headers = headers.append('enctype', 'multipart/form-data');
return this.http.post(path, formData, { headers: headers })

我还有一个 HttpInterceptor,它是设置 content-type 的,因此只有在 enctype 未设置时才进行设置。

if (!req.headers.has('enctype')) {
headersConfig['Content-Type'] = 'application/json';
}

希望这可以帮到你


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接