【问题标题】:Convert an Image to byte array in Angular (typescript)在Angular(打字稿)中将图像转换为字节数组
【发布时间】:2021-02-03 09:14:41
【问题描述】:

我有一个要求,我需要将所选图像(表单组的一部分)转换为字节数组,该字节数组需要作为发布请求的一部分发送到后端。

HTML 组件:

<div class="form-group">
                <label>Image</label>
                <input type="file" accept="image/*" class="form-control" formControlName="productImage" onchange="displaySelectedImageFunc(this);">
                <img *ngIf="displaySelectedImage" src="{{selectedImageUrl}}">
                <span class="error-message" *ngIf="itemRegistrationForm.controls.productImage.dirty && itemRegistrationForm.controls.productImage.errors">Select Image of the product</span>
</div>

【问题讨论】:

标签: angular typescript angular-forms


【解决方案1】:

尝试使用

function convertDataURIToBinary(dataURI) {
  var base64Index = dataURI.indexOf(';base64,') + ';base64,'.length;
  var base64 = dataURI.substring(base64Index);
  var raw = window.atob(base64);
  var rawLength = raw.length;
  var array = new Uint8Array(new ArrayBuffer(rawLength));

  for(i = 0; i < rawLength; i++) {
    array[i] = raw.charCodeAt(i);
  }
  return array;
}

function upload() {
  const file = document.querySelector('input[type=file]').files[0];
  
  const preview = document.getElementById('preview'); 
  const reader = new FileReader();
  let byteArray;

  reader.addEventListener("loadend", function () {
    // convert image file to base64 string
    console.log('base64', reader.result);
    preview.src = reader.result;
    byteArray = convertDataURIToBinary(reader.result);
    console.log('byte array', byteArray);
  }, false);

  if (file) {
    reader.readAsDataURL(file);
  }
}
<input type="file" id="file" accept="image/*" width="300" height="300" />

<submit onClick="upload()">Upload</submit>

<img id="preview"></img>

【讨论】:

    【解决方案2】:

    由于您可以使用 reader.readAsDataUR(file) 将图像转换为 base64 字符串,因此您可以像这样在 reader.onload 事件中提取带有 e.target.result.split('base64,')[1] 的字节部分

    const file = document.querySelector('input[type=file]').files[0])
    const reader = new FileReader();
    reader.onload = (e: any) => {
      const bytes = e.target.result.split('base64,')[1];
    };
    reader.readAsDataURL(file);
    

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 1970-01-01
      • 2015-08-16
      • 2013-05-19
      • 2021-12-19
      • 2020-12-27
      • 2018-06-14
      相关资源
      最近更新 更多