【问题标题】:How to upload multiple images in Angular 4如何在 Angular 4 中上传多个图像
【发布时间】:2019-04-12 09:56:57
【问题描述】:

我想在 Angular 中上传多张图片,但我正在上传单张图片,但现在我想上传最多 5 张图片。 对于单个图像,我有一个名为 attached_image 的参数,其中存储单个图像,但这里我想在 optionimage 参数中上传多个图像。

这是我的 component.html

<div class="col-sm-8  col-xs-6">
  <div class="file-upload upload-button">
    <input id="custom-input" type="file" (change)="handleFiles($event)" multiple>
  </div>
  <!-- <button type='button' class='btn btn-default' data-toggle="modal" data-target="#imageupload" (click)="resetCropper()">Upload Image</button> -->
  <span class="img-selected" *ngIf="isImageselected">
    <i class="fa fa-check main-content__checkmark success" id="checkmark"></i>Image sel/span>
</div>

下面的 component.ts 代码用于上传单个图像。

handleFiles = function (fileInput: Event) {
  this.imageArr = ['image/jpeg', 'image/jpg', image / png','image / gif'];

  if (fileInput.target['files'][0]['size'] > 1024000) {
    $.growl.error({ title: 'Error', message: "File can not be larger than 1 MB" });
    return;
  }
  if (!this.imageArr.includes(fileInput.target['files'][0]['type'])) {
    $.growl.error({ title: 'Error', message: "Invalid file format." });
    return;
  }

  var file: File = fileInput.target['files'][0];

  this.extention = file.name.substr((file.name.lastIndexOf('.') + 1)).toLowerCase();
  var reader = new FileReader();
  reader.onload = this._handleReaderLoaded.bind(this);
  reader.readAsBinaryString(fileInput.target['files'][0]);
}

_handleReaderLoaded(readerEvt) {
  var binaryString = readerEvt.target.result;
  this.base64textString = btoa(binaryString);
  this.attached_image = 'data:image/jpeg;base64,' + this.base64textString;
  if (this.attached_image) {
    this.flashMsg = "Image uploaded successfully!";
  }
}

非常感谢您的帮助。

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    选择多个文件后,您将在fileInput.target['files'] 数组中拥有这些文件。您需要循环并调用例如validateFile()

    var files = fileInput.target['files'];
    
    if (files.length > 5) 
    {
      // Error max 5 files
    }
    
    for (i=0; i < files.length; i++) 
    {
      validateFile(files[i])
    }
    
    ...
    
    function validateFile(file) {
      if (fileInput.target['files'][0]['size'] > 1024000) {
         $.growl.error({ title: 'Error', message: "File can not be larger than 1 MB });
            return;
      }
      if (!this.imageArr.includes(fileInput.target['files'][0]['type'])) {
         $.growl.error({ title: 'Error', message: "Invalid file format." });
         return;
      }
    }
    

    【讨论】:

    • 感谢您的回复
    • 但这里我想在 optionimage 参数和单个图像 attach_image 参数中设置五个图像
    • 请问我到目前为止还没有找到我的问题的解决方案吗?
    猜你喜欢
    • 1970-01-01
    • 2018-06-30
    • 2018-03-12
    • 2019-05-27
    • 2013-07-23
    • 1970-01-01
    • 2021-08-01
    • 2018-08-01
    • 1970-01-01
    相关资源
    最近更新 更多