角使用ng2-file uploader将多个文件转换为base64字符串

时间:2019-01-24 13:03:06

标签: angular

在这里,我尝试使用ng2-文件上传程序以base 64格式发送多个图像或pdf

代码用7号角表示:

public uploader: FileUploader = new FileUploader({
  url: URL,
  allowedMimeType: ['application/pdf', 'image/jpeg', 'image/png'],

});

这是我尝试转换为base 64并将值以数组格式推送到imageData的代码

this.imageData = [];
let fileCount: number = this.uploader.queue.length;
if (fileCount > 0) {
  this.uploader.queue.forEach((val, i, array) => {
    let fileReader = new FileReader();
    fileReader.onloadend = (e) => {
      this.imageData.push(fileReader.result);
    }
    console.log(this.imageData, "imageData") // Here somtimes i get an empty data
  });

我面临的问题是,当我选择文件时,必须从系统中选择一个文件,如果我尝试选择多个文件,那么它会提供空数据

如果获取数据,则每次提交时都会不断重复。

这是html部分:

<div class="form-group clearfix">
  <label class="control-label" for="exampleInputFile">
                      <strong>{{'Upload a file' | translate}}</strong>
                    </label>
  <input required #uploader1Input type="file" ng2FileSelect [uploader]="uploader" accept="image/png,image/jpg,image/jpeg,image/gif,application/pdf" name="photoid" multiple />
  <h3>Upload queue</h3>
  <p>Queue length: {{ uploader?.queue?.length }}</p>
</div>

<div class="clearfix">
  <div class="preview-wrapper image">
    <div class="preview-img" *ngFor="let item of uploader.queue ; let i = index">
      <img src mediaPreview *ngIf="item?._file.type.startsWith('image')" [media]="item?._file" class="media-object" />
      <!-- PDF -->
      <img *ngIf="item?._file.type === 'application/pdf'" src="assets/images/pdf.svg" mediaPreview [media]="item._file" class="image-pdf">
      <div>
        <button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#removeDocumentModal" data-backdrop="false" (click)="removePhotoId(index)">
                            <span class="fa fa-times"></span>
                          </button>
      </div>
    </div>
  </div>
</div>

0 个答案:

没有答案