angular5 上传多个文件

html代码:

                       

                                        //singleFile绑定的就是file的name

                                       

                                       

                                        //

                                           // {{uploadProgress}}% 

                                        //

                         

ts代码:

//声明
 uploadProgress: any;

  singleFile = [];

  // 上传多个

  upload(file: HTMLInputElement) {

    // const token = localStorage.getItem('token');

    let headers: HttpHeaders = new HttpHeaders();

    // headers = headers

    //  .set('Cache-Control', 'no-cache')

    //  .set('Authorization', 'Bearer ' + token);

    if (file.value.length === 0) {

      return;

    }

    const files: FileList = file.files;

    const fileLength = files.length;

    const formData: FormData = new FormData();

    for (let index = 0; index < fileLength; index++) {

      // 多个file

      const singleFile = files.item(index);

      // files 这个名字和spring mvc controller参数的名字要对应

      formData.append('upfile', singleFile);

      this.singleFile.push(singleFile.name);

    }

    formData.append('filecategory', 'grSupportant');

    // for (let singleFile of files.item) {

    //  formData.append(singleFile.name, singleFile);

    // }

    // formData.append('file', file.files[0]);

    const url = 'http://localhost:8764/api/v1/user/fileUpload';

    // const req = new HttpRequest('POST', url, formData, {

    //  reportProgress: true, headers: headers

    // });

    // this.http.request(req).subscribe(event => {

    //  if (event.type === HttpEventType.UploadProgress) {

    //    this.uploadProgress = Math.round(100 * event.loaded / event.total);

    //  } else if (event instanceof HttpResponse) {

    //    console.log('Files uploaded!');

    //    this.singleFile = [...this.singleFile];

    //    console.log(this.singleFile);

    //  }

    // });

    this.http.post(url, formData, { headers: headers }).subscribe(data => {

      console.log(data);

      if (data['code'] == 0) {

        this.singleFile = [...this.singleFile];

      }

    });

  }

你可能感兴趣的:(angular5 上传多个文件)