Skip to content Skip to sidebar Skip to footer

Angular 2 - Model Driven Form With Input File (file Upload)

I am currently developing in Angular 2 a form that allows a user to update his profile: email and password. user-edit.component.html:

Solution 1:

File Uploading in angular2,

In fact, the Http class doesn't support that at the moment.

You need to leverage the underlying XHR object to do that:

import {Injectable} from'angular2/core';
import {Observable} from'rxjs/Rx';

@Injectable()
exportclassUploadService {
  constructor () {
    this.progress$ = Observable.create(observer => {
      this.progressObserver = observer
    }).share();
  }

  private makeFileRequest (url: string, params: string[], files: File[]): Observable {
    returnObservable.create(observer => {
      letformData: FormData = newFormData(),
        xhr: XMLHttpRequest = newXMLHttpRequest();

      for (let i = 0; i < files.length; i++) {
        formData.append("uploads[]", files[i], files[i].name);
      }

      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            observer.next(JSON.parse(xhr.response));
            observer.complete();
          } else {
            observer.error(xhr.response);
          }
        }
      };

      xhr.upload.onprogress = (event) => {
        this.progress = Math.round(event.loaded / event.total * 100);

        this.progressObserver.next(this.progress);
      };

      xhr.open('POST', url, true);
      xhr.send(formData);
    });
  }
}

See this plunkr for more details: https://plnkr.co/edit/ozZqbxIorjQW15BrDFrg?p=info.

There is a an issue and a pending PR regarding this in the Angular repo:

took answer from here

Post a Comment for "Angular 2 - Model Driven Form With Input File (file Upload)"