使用$ http发送带角度的multipart / form-data文件

时间:2016-03-01 11:48:25

标签: angularjs http file-upload http-headers multipartform-data

我知道有很多问题,但我无法解决这个问题:

我想在multipart / form-data

中将文件从输入上传到服务器

我尝试了两种方法。第一:

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

导致例如对于图像

Content-Type:image/png

虽然它应该是multipart / form-data

和另一个:

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

但是这要求一个边界标题,我认为不应该手动插入...

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

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

但我不希望我的所有帖子都是多部分/表单数据。默认值应为JSON

4 个答案:

答案 0 :(得分:57)

看一下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(){
        });
    }

答案 1 :(得分:24)

以下是Angular 4& S的更新答案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
    });
}

Angular 4解决方案:

// 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
    });
}

答案 2 :(得分:2)

在Angular 6中,您可以执行以下操作:

在您的服务文件中:

 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);
    });
}

答案 3 :(得分:1)

在角度 9, 之前尝试过“内容类型”:未定义,但对我不起作用 然后 我尝试了下面的代码,它就像一个文件对象的魅力

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