Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

angular - How to upload file in Angular2

I have to submit a form along with image. i have tried this code (with multiple ways) but did't work for me. is there anyone having working demo of file uploading using angular2 please help me out.

component.html

    <form class="form-horizontal" role="form" >

        <div class="form-group">
            <label class="control-label col-sm-4" for="myname" style="">Name<span class="asterisk">*</span></label>
            <div class="col-sm-7">
                <div>
                    <input type="text" class="form-control" id="myname"
                    [(ngModel)]="myfile.name">                        
                </div>                  
            </div>                               
        </div>        


        <div class="form-group">
            <label class="control-label col-sm-4" for="myimage">Image</label>
            <div class="col-sm-7">
                <div>
                    <input type="file" (change)="fileChangeEvent($event)" placeholder="Upload file..." />                         
                </div>   
            </div>
        </div>


        <div class="form-group">        
        <div class="text-center">
            <button type="button" (click)="upload()">Upload</button>             
        </div>
        </div>
  </form>

component.ts

     myfile={
                "name":"Mubashshir",               
                "image":''
     }

     fileChangeEvent(fileInput: any){
        this.myfile.image = fileInput.target.files;        
     }

     upload(){
          this.base_path_service.PostRequest('http://128.199.190.109/api/school/schoolDetail/',this.myfile)
            .subscribe(
                data => {
                            console.log("data submitted");                        
                        },
                err => console.log(err),
                () =>{
                     console.log('Authentication Complete');                    

                }
            );
      }
question from:https://stackoverflow.com/questions/35985347/how-to-upload-file-in-angular2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()
export class UploadService {
  constructor () {
    this.progress$ = Observable.create(observer => {
      this.progressObserver = observer
    }).share();
  }

  private makeFileRequest (url: string, params: string[], files: File[]): Observable {
    return Observable.create(observer => {
      let formData: FormData = new FormData(),
        xhr: XMLHttpRequest = new XMLHttpRequest();

      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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...