9

Do angular2 supports multipart form submit, any example available?

Any link to docs specific to this is much appreciated

See post from angular github https://github.com/angular/angular/issues/6030

**** Updated later with Working Demo using XMLHttpRequest ****

Any example showcasing sending FormData as part of http,

Below is a draft code which works fine for me but like to know if same supported in http

HTML

  <input id="single_f_fileup" [(ngModel)]="model.image" type="file" (change)="selectFile($event)" name="single_fileup" />

ANGULAR2

selectFile($event): void {
 var files = $event.target.files || $event.srcElement.files;
        var file = files[0];
        let formData = new FormData();
        formData.append("single_fileup", file);
        formData.append('key1', 'value1');
        formData.append('key2', 'value2');
       var req = new XMLHttpRequest();
       req.open("POST", "/api/fileupload");
       req.send(formData);
}

NODEJS 6.2

var multer  = require('multer');
var storage = multer.memoryStorage();
var upload = multer({ storage: storage });
  router.post('/api/fileupload', upload.single('single_fileup'), function(req, res, next){
        console.log(req.body,req.file);
});

How to make below code work?

 this.http.post('/api/fileupload', formData)
            .map(this.extractData)
            .catch(this.handleError);

2 Answers 2

14

Sample snippet to pass formData which contains image

https://gist.github.com/arciisine/ee57727e56cbc5e83739b2c24fd69658

https://github.com/angular/angular/issues/6030

import { Component, Input, AfterViewInit } from '@angular/core';
import { NgModel, DefaultValueAccessor, NgControl } from '@angular/forms';
import { Http, Headers, RequestOptions } from '@angular/http';

@Component({
  selector: 'app-file-uploader',
  template: '<input type="file" (change)="updated($event);">',
  providers: [NgModel, DefaultValueAccessor]
})
export class FileUploaderComponent implements AfterViewInit {

  static ROOT = '/rest/asset';

  @Input() private companyId: string = '';
  private value: string;
  private changeListener: Function;

  constructor(private http: Http, private input: NgControl) {
    this.input.valueAccessor = this;
  }

  ngAfterViewInit() {
  }

  writeValue(obj: any): void {
    this.value = obj;
  }

  registerOnChange(fn: any): void {
    this.changeListener = fn;
  }

  registerOnTouched(fn: any): void {

  }

  updated($event) {
    const files = $event.target.files || $event.srcElement.files;
    const file = files[0];
    const formData = new FormData();
    formData.append('file', file);

    const headers = new Headers({});
    let options = new RequestOptions({ headers });
    let url = FileUploaderComponent.ROOT + (this.companyId ? '/' + this.companyId : '');

    this.http.post(url, formData, options).subscribe(res => {
      let body = res.json();
      this.value = body.filename;

      if (this.changeListener) {
        this.changeListener(this.value);
      }
    });
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Good answer, most answers I have seen use Javascript not angular. Might I suggest adding critical code in your answer so that when the links become broken the answer remains relevant.
4

ng2-file-upload will be your guide for multipart upload. AngularJs also have ng-file-upload in case you want to have a look at directive.

4 Comments

Can i do normal form post with fields and files at same time
Yes, you can. Rememeber to override` onBeforeUploadItem inside ngInit()` to capture all the data before submission.
Does ng2-file-upload supports to send the chunks and for large files?
Hey buddy, Sorry it's been a while since I have used it. You might want to check with their documentation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.