使用 $http 使用 angular 发送 multipart/form-data 个文件

Send multipart/form-data files with angular using $http

我知道有很多关于此的问题,但我无法让它工作:

我想将文件从输入上传到 multipart/form-data

中的服务器

我试过两种方法。第一:

headers: {
  'Content-Type': undefined
},

这导致例如对于图像

Content-Type:image/png

虽然应该是 multipart/form-data

另一个:

headers: {
  'Content-Type': multipart/form-data
},

但这需要一个边界 header,我认为不应该手动插入...

解决这个问题的干净方法是什么? 我读到你可以做到

$httpProvider.defaults.headers.post['Content-Type'] = 'multipart/form-data; charset=utf-8';

但我不希望我所有的帖子都是 multipart/form-data。默认值应该是 JSON

看看 FormData 对象: https://developer.mozilla.org/en/docs/Web/API/FormData

this.uploadFileToUrl = function(file, uploadUrl){
        var fd = new FormData();
        fd.append('file', file);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(){
        })
        .error(function(){
        });
    }

这是 Angular 4 和 5 的更新答案。TransformRequest 和 angular.identity 已删除。我还包括在一个请求中将文件与 JSON 数据合并的功能。

Angular 5 解:

import {HttpClient} from '@angular/common/http';

uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
  // Note that setting a content-type header
  // for mutlipart forms breaks some built in
  // request parsers like multer in express.
  const options = {} as any; // Set any options you like
  const formData = new FormData();

  // Append files to the virtual form.
  for (const file of files) {
    formData.append(file.name, file)
  }

  // Optional, append other kev:val rest data to the form.
  Object.keys(restObj).forEach(key => {
    formData.append(key, restObj[key]);
  });

  // Send it.
  return this.httpClient.post(uploadUrl, formData, options)
    .toPromise()
    .catch((e) => {
      // handle me
    });
}

Angular4 解:

// Note that these imports below are deprecated in Angular 5
import {Http, RequestOptions} from '@angular/http';

uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
  // Note that setting a content-type header
  // for mutlipart forms breaks some built in
  // request parsers like multer in express.
  const options = new RequestOptions();
  const formData = new FormData();

  // Append files to the virtual form.
  for (const file of files) {
    formData.append(file.name, file)
  }

  // Optional, append other kev:val rest data to the form.
  Object.keys(restObj).forEach(key => {
    formData.append(key, restObj[key]);
  });

  // Send it.
  return this.http.post(uploadUrl, formData, options)
    .toPromise()
    .catch((e) => {
      // handle me
    });
}

在Angular6中,你可以这样做:

在您的服务文件中:

 function_name(data) {
    const url = `the_URL`;
    let input = new FormData();
    input.append('url', data);   // "url" as the key and "data" as value
    return this.http.post(url, input).pipe(map((resp: any) => resp));
  }

在 component.ts 文件中: 在任何函数中说 xyz,

xyz(){
this.Your_service_alias.function_name(data).subscribe(d => {   // "data" can be your file or image in base64 or other encoding
      console.log(d);
    });
}

在angular9, 之前尝试 'Content-Type': 未定义,但对我不起作用 然后 我尝试了下面的代码,它就像一个文件对象的魅力

const request = this.http.post(url, data, {
      headers: {
        'Content-Type': 'file'
      },
    });

不要设置重置更新内置的FormDataContent-Type。它会被解决。在 Angular 7 中有效。

虽然有一个 Auth-Interceptor 但我没有让它设置、更改或重置我的 Content-Type header 我的 post 请求。就这样吧,问题就解决了。

Here is my auth interceptor image where I by passed my request

In Angular 13 (~13.0.0)不需要指定Content-Type的请求。

some.service.ts:

public sendFiles(data: any): Observable<any> {
    const formData = new FormData();

    data.files.forEach((file: File) => {
      formData.append('files', file);
    });
    
    const url: string = <YOUR_API_URL>;

    return this.http.post<any>(url, formData);
}
  • 设置Content-Type字段为以下值会导致错误:
    • 'file'
    • 未定义(不能激活严格模式)
    • 'multipart/form-data'