【问题标题】:Return File from ngx-image-cropper to upload - Angular从 ngx-image-cropper 返回文件以上传 - Angular
【发布时间】:2020-07-17 09:29:39
【问题描述】:

我正在使用ngx-image-cropper 来裁剪我的图像。我需要从ngx-image-cropper 检索裁剪的图像以上传。但是,我无法通过此检索 File 对象。

这是我用来在用户裁剪图像时触发的代码,

imageCropped(event: ImageCroppedEvent) {
    this.croppedImage = event.base64;
    this.cropperHeight = event.height;
    this.cropperWidth = event.width;
    this.croppedEvent =event.file;//This is how i tried to get file
}

当我尝试上传文件时,它出现了一些错误。所以最好提供一种从ngx-image-cropper获取文件对象的方法

【问题讨论】:

  • 你能制作一个 Stackblitz 或展示事件对象吗?
  • 看起来这在 3.0 版本中已被删除。 github.com/Mawi137/ngx-image-cropper/pull/314
  • 有办法的。我们可以返回裁剪图像的 base64。然后我们可以将其转换为 blob(base64 到 blob)并使用该 blob 创建文件。
  • @nipun-kavishka 它正在创建一个损坏的文件。

标签: angular image file blob node-modules


【解决方案1】:

包中包含方法base64ToFile

// Import the method:

import { ImageCroppedEvent, base64ToFile } from 'ngx-image-cropper';

.....
imageCropped(event: ImageCroppedEvent) {
    this.croppedImage = event.base64;
    let File = base64ToFile(this.croppedImage);
}

来源:https://github.com/Mawi137/ngx-image-cropper/releases/tag/3.0.0

【讨论】:

  • 这应该是答案
  • 如何连接一个 HTML 按钮来调用这个函数?
  • 这会返回 Blob 类型的对象,但我们需要文件类型才能做到这一点。或者当我们将图像传递给 api 时是否相同
  • 要使其成为文件而不是 Blob,您可以 file : File = new File([fileBlob], originalFile.name,{lastModified: originalFile.lastModified, type: originalFile.type});
【解决方案2】:

要将裁剪后的图像作为文件而不是 base64 字符串返回,请添加以下内容:


import { ImageCroppedEvent, base64ToFile } from 'ngx-image-cropper';

  imageCropped(event: ImageCroppedEvent) {
    // Preview
    this.croppedImage = event.base64;

    const fileToReturn = this.base64ToFile(
      event.base64,
      this.data.imageChangedEvent.target.files[0].name,
    )

    return fileToReturn;
  }


  base64ToFile(data, filename) {

    const arr = data.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    let u8arr = new Uint8Array(n);

    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }

    return new File([u8arr], filename, { type: mime });
  }

【讨论】:

    【解决方案3】:

    我解决了将原始文件发送到函数并在 image-cropper crop( originalFile: File ) 函数上创建一个新的 File 实例:

    import { ImageCroppedEvent, base64ToFile } from 'ngx-image-cropper';
    ...
    crop(originalFile): File {
       ...
       ...
       output.base64 = this.cropToBase64(cropCanvas);
       if(originalFile){
         const file = new File([base64ToFile(output.base64)], originalFile.name, {lastModified: originalFile.lastModified, type: originalFile.type});
         return file;
       }
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-05
      • 2020-11-01
      • 2021-05-04
      • 2019-03-08
      相关资源
      最近更新 更多