简体   繁体   English

如何从 Angular NGX Dropzone 中的图像中提取 base64

[英]How to extract the base64 from an image in Angular NGX Dropzone

Hey guys I am using NGX Dropzone and I notice when I drag an image into the viewer it is in base64, but when I try to read the console.log(event.addedFiles);嘿伙计们,我正在使用 NGX Dropzone,当我将图像拖入查看器时,我注意到它是 base64,但是当我尝试读取console.log(event.addedFiles); I have no information being passed to me with the base64 value.我没有使用 base64 值传递给我的信息。 Here's an example of what I get back这是我返回的示例

[File]
  0: File
     lastModified: 1625149167659
     lastModifiedDate: Thu Jul 01 2021 10:19:27 GMT-0400 (Eastern Daylight Time) {}
     name: "210534431_764639924207804_238792847075232344_n.jpeg"
     size: 101133
     type: "image/jpeg"
     webkitRelativePath: ""
     __proto__: File
     length: 1
     __proto__: Array(0)

I have another piece of code which I have been using that transforms a URL into a base64 string.我有另一段代码,我一直在使用它将 URL 转换为 base64 字符串。 But thats useless to me since the URL can also be shared and opened by anyone from anywhere.但这对我来说没用,因为 URL 也可以被任何人从任何地方共享和打开。 However my local image in my computer is only available to me, unless I transform it into base64 which is a string I can save in a database.但是,我计算机中的本地图像仅对我可用,除非我将其转换为 base64,这是一个可以保存在数据库中的字符串。

This is the script这是脚本

imageToShow: any;

onURLinserted() {
  this.getImage(this.thumb.name).subscribe(data => {
    this.createImageFromBlob(data);     
  }, error => {
    console.log("Error occured",error);
  });

  console.log("Data: ", this.thumb.name);
}

getImage(imageUrl: string): Observable<Blob> {
  return this.http
    .get<Blob>(imageUrl, { observe: 'body', responseType: 'blob' as 'json' })
}

createImageFromBlob(image: Blob) {
  let reader = new FileReader(); //you need file reader for read blob data to base64 image data.
  reader.addEventListener("load", () => {
      this.imageToShow = reader.result; // here is the result you got from reader which I use to view the image
      this.selectedRowData.photo = reader.result; // this is my ngModel read by my HTML input fields
  }, false);

  if (image) {
    reader.readAsDataURL(image);
  }
}

//In my HTML code
<img [src]="imageToShow" alt=""> 

All I am really trying to do is extract the base64 information from the image dragged in there into imageToShow either by using this code if it helps or something similar OR maybe the cdk drag an drop already has a prop that I dont know about我真正想做的就是从拖动到 imageToShow 中的图像中提取 base64 信息,如果有帮助,或者使用类似的代码,或者可能 cdk 拖放已经有一个我不知道的道具

How do I know that the base64 is even available?我怎么知道 base64 甚至可用? When I drag an image in it, and I inspect it in the dev tool I can see the src="data:image/jpeg;base64,random stuff..."当我在其中拖动图像并在开发工具中检查它时,我可以看到 src="data:image/jpeg;base64,random stuff..."

Wish I could put some test code here but I will need the dropzone library for it希望我可以在这里放一些测试代码,但我需要 dropzone 库

Looks like ngx-dropzone does not have a prop that provides bas64String.看起来 ngx-dropzone 没有提供 bas64String 的道具。 You can use readAsDataURL to get base64String.您可以使用 readAsDataURL 来获取 base64String。 The readAsDataURL is used to read the contents of the Blob or File. readAsDataURL 用于读取 Blob 或文件的内容。 When the loadend is triggered.当 loadend 被触发时。 At that time, the result attribute contains the data as a data: URL representing the file's data as a base64 encoded string.当时,result 属性包含数据作为 data: URL,将文件数据表示为 base64 编码字符串。

The below code worked for me.下面的代码对我有用。

html file html文件

    <div class="custom-dropzone" ngx-dropzone [accept]="'image/jpeg,image/jpg,image/png,image/gif'"
                  (change)="onSelect($event)">
                  <ngx-dropzone-label>
                    <div>
                      <h2>Upload photo</h2>
                    </div>
                  </ngx-dropzone-label>
                  <ngx-dropzone-image-preview ngProjectAs="ngx-dropzone-preview" *ngFor="let f of files" [file]="f"
                    [removable]="true" (removed)="onRemove(f)">
                  </ngx-dropzone-image-preview>
   </div>

.ts file .ts 文件

onSelect(event) {
        this.files.push(...event.addedFiles);
        if (this.files && this.files[0]) {
          for (let i = 0; i < this.files.length; i++) {
           this.fileToBase64(this.files[i])
            .then(result=>{
              const base64String = result.replace('data:', '')
              .replace(/^.+,/, ''); // To remove data url part
              this.postMultimedias.push({ name:this.files[i].name,content: 
               base64String});//postMultimedias is a array which holds image name and bas64String
            });         
          }
        }
      }

 fileToBase64 = (file:File):Promise<string> => {
    return new Promise<string> ((resolve,reject)=> {
         const reader = new FileReader();
         reader.readAsDataURL(file);
         reader.onload = () => resolve(reader.result.toString());
         reader.onerror = error => reject(error);
     })
    }

onRemove(event) {
    let position = this.files.indexOf(event);
    this.postMultimedias.splice(position, 1);
    this.files.splice(position, 1);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM