DEV Community

swipra
swipra

Posted on

How to get the unzipping done first before executing the observable post

Need to get unzipped files and store into an array files. Then need to upload the array of files. There is a need of some delay between the unzipping using loadAsSync and post ( to import). Here Post is executed before unzipping. Any help is much appreciated

code-snippets:

selectedfiles: File[] = [];

// Unzip and stores files into selectedfiles. 

readZip(file: any) {
    var jsZip = require('jszip')
    this.selectedfiles = [];

    jsZip.loadAsync(file).then((zip) => {
      Object.keys(zip.files).forEach((filename) => {
        zip.files[filename].async('blob').then((fileData) => {

          if (!zip.files[filename].dir) {
            const tmp = new File([fileData], filename);
            this.selectedfiles.push(tmp);
          }
        });
      });
    });
  }

// To upload the selected zip file
  upload(files: FileList): Observable<HttpEvent<Blob>> {
    const url = `${this.apiroot}/device/wifi/settings`;
    const formData = new FormData();

    this.readZip(files[0]) //stores files into selectedfiles 

     this.selectedfiles.forEach((value) => {
        formData.append('file', value);
      });

    return this.http.post<HttpResponse<DSettings>>(url, formData, { observe: 'events', reportProgress: true }).pipe(
      tap(() => {
        this.log('uploaded settings');
        this.selectedfiles = [];
      }),
      catchError(this.handleError<DSettings>('upload'))
    );
  }

Enter fullscreen mode Exit fullscreen mode

Top comments (0)