Индикатор выполнения отображается только в первый раз при последовательной загрузке файлов под углом 6 - PullRequest
0 голосов
/ 14 февраля 2019

В моем приложении Angular у меня есть отдельная форма для загрузки картинки профиля.Когда я загружаю новое изображение, появляется модальное подтверждение, и после подтверждения на странице отображается индикатор выполнения, который исчезает после 100% завершения.Если я попытаюсь загрузить другое изображение, не переходя на другую маршрутизацию (все еще на той же странице), процесс будет происходить так же, как и предыдущий, за исключением индикатора выполнения.во второй раз индикатор выполнения не будет виден.Мне нужно показать индикатор выполнения при каждой загрузке файла.Мои коды приведены ниже.

.html файл

 <div class="col-md-5 col-12 profile-content">
  <form #imageForm enctype="multipart/form-data" novalidate>
    <div class="img-content">
      <div class="avatar-upload">
        <div class="avatar-edit">
          <input (change)="imagesChange($event.target.files)" type='file' id="fileName" name="fileName"
                 accept=".png, .jpg, .jpeg"/>
          <label for="fileName"></label>
        </div>
        <div class="avatar-preview">
          <div id="imagePreview" *ngIf="model.profilePic == null"
               [style.background-image]="defaultBgImageVariable"></div>
          <div *ngIf="model.profilePic" id="imagePreview"
               [ngStyle]="{'background-image':'url(' + model.profilePic + ')'}"></div>
        </div>
      </div>
      <div id="avatar" class="img-upload-progress" *ngIf="isAvatarUploading">
        <div class="progress">
          <div class="progress-bar" id="progressBar"></div>
        </div>
        <p id="uploadText">uploading...</p>
      </div>
    </div>
  </form>
</div>

модальный в том же файле .html

<div class="favorite-noti">
<div id="avatarUploadConfirm" class="modal fade" tabindex="-1" role="dialog" 
 aria-labelledby="favoriteNotification"
   aria-hidden="true">
<div class="modal-dialog modal-confirm">
  <div class="modal-content">
    <div class="modal-body">
      <h4>Do you want to upload profile picture ?.</h4>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn  btn-confirm" (click)="updateAvatar()">Upload</button>
      <button type="button" class="btn btn-info" (click)="cancelModal()">Cancel</button>
    </div>
  </div>
</div>

.ts файл

 imagesChange(files) {
 (<any>$('#avatarUploadConfirm')).modal('show');
 this.myAvatar = files;
 }

updateAvatar() {
(<any>$('#avatarUploadConfirm')).modal('hide');
this.handleFileInput(this.myAvatar);
}

cancelModal() {
(<any>$('#avatarUploadConfirm')).modal('hide');
}

handleFileInput(files) {
this.isAvatarUploading = true;
this.fileToUpload = files.item(0);
const formData = new FormData();
console.log('image-height', files.item.naturalHeight);
formData.append('fileName', this.fileToUpload, this.fileToUpload.name);

const user = this.authService.getUserFromLocalStorage();
if (user !== null) {
  const url = `customers/profile-pic/${user.id}`;
  this.restClientService.fileUpload(url, formData).subscribe(
    response => {
      console.log(response);

      const imagePreview: HTMLElement = document.getElementById('imagePreview');
      imagePreview.style.backgroundImage = 'url(\'' + response.message.profilePic + '\')';
      this.model.profilePic = response.message.profilePic;

      const elem = document.getElementById('progressBar');
      const txt = document.getElementById('uploadText');
      var width = 1;
      const id = setInterval(frame, 10);

      function timeoutToMissbar() {
        document.getElementById('avatar').style.display = 'none';
      }

      function frame() {
        if (width >= 100) {
          clearInterval(id);
          txt.innerHTML = 'Done 100%';
          setTimeout(timeoutToMissbar, 2500);
        } else {
          width++;
          elem.style.width = width + '%';
          // elem.innerHTML = width * 1 + '%';
        }
      }

    }
  );
 }
}

Мне нужна помощь, чтобы показать индикатор выполнения при каждой загрузке файла.

1 Ответ

0 голосов
/ 14 февраля 2019

Вы устанавливаете отображение на none и не устанавливаете его для отображения снова.Добавление приведенного ниже кода в начале handleFileInput должно исправить это.

setTimeout(() => {
  document.getElementById('avatar').style.display = 'initial';
  document.getElementById('uploadText').innerText = 'uploading...';
}, 0);

Лучший способ - Вы можете добиться скрытия и отображения части, используя одну и ту же переменную isAvatarUploading вместо того, чтобы дополнительно использовать стили.Вам нужно использовать Subject для этого

public isAvatarUploading$ = new Subject();

handleFileInput() {
   this.isAvatarUploading = true;

   let timeoutToMissbar = () => {
       // document.getElementById('avatar').style.display = 'none';
        this.isAvatarUploading$.next(false);
   }

И в html

*ngIf="isAvatarUploading$ | async"
...