在Angular2中构建multipart / form-data POST请求并验证输入类型File

时间:2016-04-27 21:12:44

标签: javascript angular typescript post angular2-forms

我有一个图像(base64),我需要通过POST请求发送(并等待响应)。 POST请求必须为Content-Type:multipart/form-data。 图片必须为Content-Type: image/jpg

POST请求应如下所示:

POST https://www.url... HTTP/1.1
Content-Type: multipart/form-data; boundary=-------------------------acebdf13572468
User-Agent: Fiddler
Host: www.host.com
Content-Length: 199640

---------------------------acebdf13572468
Content-Disposition: form-data; name="fieldNameHere"; filename="Nikon Digital SLR Camera D3100 14.2MP 2.jpg"
Content-Type: image/jpeg

以二进制图像数据作为内容正文。

我正在尝试使用角度2的Http Post方法,但我不太确定如何生成请求。 这就是我所拥有的:

let body = atob(imageData);
let headers = new Headers({'Content-Type': 'multipart/form-data'});
let options = new RequestOptions({headers: headers});

this._http.post(url, body, options)
.map(res=>{
  //do stuff
});

我可以说我错过了它的一部分,但我不知道我需要做什么来给二进制图像数据它的内容配置&输入等。

3 个答案:

答案 0 :(得分:4)

Form template

<form id="form" name="file" [formGroup]="FileFormGroup"(submit)="addFrom($event, FileFormGroup)" method="post">  

   <input spellcheck="true" formControlName="Demo" name="Demo" type="text"/>
   <input type="file" accept="image/*" id="file" name="File"/>
   <input formControlName="File" type="hidden"/>

</form>

<强> Ts

   import {FormGroup, FormBuilder, FormControl, Validators} from '@angular/forms';

   import {ValidatorFn} from '@angular/forms/src/directives/validators';

   public FileFormGroup: FormGroup; /* variable */

   constructor(public fb: FormBuilder) {}

   ngOnInit() {
      this.FileFormGroup = this.fb.group({
      Demo: ["", Validators.required],
      File: ["", this.fileExtension({msg: 'Please upload valid Image'})]
     });
   }

   public addFrom(event: Event, form: FormGroup): void {

   if(form.valid && form.dirty) {

   let formTemp: HTMLFormElement <HTMLFormElement>document.querySelector('#form');

   let formData: FormData = new FormData(formTemp);

   let xhr: XMLHttpRequest = this.foo(formData);

    xhr.onreadystatechange = () => {
      if(xhr.readyState === 4) {
        if(xhr.status === 201) {
           console.log("Success");
        } else {
           console.log("Error");
        }
      }
    }
  }}

    // Foo function
     public Foo(formData){
         let url: Foo;
         let xhr: XMLHttpRequest = new XMLHttpRequest();
         xhr.open('POST', url, true);

         // enctype For Multipart Request
          xhr.setRequestHeader("enctype", "multipart/form-data");

          // IE bug fixes to clear cache
          xhr.setRequestHeader("Cache-Control", "no-cache");
          xhr.setRequestHeader("Cache-Control", "no-store");
          xhr.setRequestHeader("Pragma", "no-cache"); 

          xhr.send(formData);
          return xhr;
     }

     /* validation function to check proper file extension */

  public fileExtension(config: any): ValidatorFn {
    return (control: FormControl) => {

      let urlRegEx: RegExp = /\.(jpe?g|png|gif)$/i;

      if(control.value && !control.value.match(urlRegEx)) {
        this.deleteImg = false;
        return {
          invalidUrl: config.msg
        };
      } else {
        return null;
      }
    };
  }

答案 1 :(得分:0)

此处与此问题类似:Angular 2 - Post File to Web API

Angular2还不支持multipart / form-data POST请求,因此我决定使用jQuery来实现它,然后将其转换为RxJs Observable(subject),使其具有与http.post函数相同的类型在Angular2中应该有:

var clock = { 
    get now() { 
        return Date.now();
    }
 };

console.log(clock.now);   // returns live time

答案 2 :(得分:0)

请查看此工作示例(不是我的):https://plnkr.co/edit/ViTp47ecIN9kiBw23VfL?p=preview

1 - 不要更改或设置Content-Type

2 - 使用FormData发送参数

3 - 将此添加到app.module.ts:

import { HttpModule, RequestOptions, XHRBackend, ConnectionBackend, Http, Request, RequestOptionsArgs, Response, Headers } from '@angular/http';
@Injectable()
export class HttpInterceptor extends Http {
    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) 
    {
        super(backend, defaultOptions);
        defaultOptions.headers = new Headers();
        defaultOptions.headers.append('Content-Type', 'application/json');
    }
}