在TypeScript中将图像转换为base64字符串

16

我正试图从 Angular 5 发送 base64 字符串到我的 API。

首先,我需要将它从图片转换为 base64。在查阅了互联网和 MDN 后,我开发了一种方法。

  OnIDChange(event) {
    var file = event.target.files[0];
    var reader = new FileReader();
    reader.onloadend = this.handleReaderLoaded.bind(this, "Id");
    reader.readAsBinaryString(file);
  }
    handleReaderLoaded(readerEvt:any, indicator: string) {
     var binaryString = readerEvt.target.result;
     if (indicator == "Id") {
       this.Model.IDPhoto = btoa(binaryString);
     }
  }
我需要在模型属性中存储此base64以在API中发布它,但在控制台中会出现错误“无法读取未定义的属性'result'”。
如何将图像转换为base64,如果有其他更适合的方法(任何npm包或其他东西),请让我知道。
谢谢您提前。
MDN参考链接 MDN 链接
3个回答

39

你需要使用readAsDataURL()

function getBase64(event) {
   let me = this;
   let file = event.target.files[0];
   let reader = new FileReader();
   reader.readAsDataURL(file);
   reader.onload = function () {
     //me.modelvalue = reader.result;
     console.log(reader.result);
   };
   reader.onerror = function (error) {
     console.log('Error: ', error);
   };
}

不要使用console.log,我该如何将这个base64值赋给模型属性? - Tanwer
您可以将base64内容分配给模型对象以进行API提交。已更新代码。 - Suresh Kumar Ariya
1
这就是问题所在,模型对象并不像你建议的那样在reader.onload函数内可用。 - Tanwer
4
少做了几处修改之后,它就可以工作了——“reader.result.toString().split(',')[1]”,谢谢。 - Tanwer
这里有一个问题,如果浏览器禁用了JavaScript,它还能工作吗? - Tanwer
如果JavaScript被禁用,那么所有的网站都将无法工作。 - Suresh Kumar Ariya

2
这是我做的上传个人资料图片的操作,我还检查了大小是否小于512KB,然后在下一个函数中将该图片发布到我的API。我使用了FileReader()和readAsDataURL()将文件转换为base64格式。
/* On Change Profile image*/    
    onProfileChange(event:any) {
        if(event.target.files && event.target.files[0]) {
            if(event.target.files[0].type && event.target.files[0].type.split('/')[0] == ["image"] && event.target.files[0].size <= 512000){
                this.file = event.target.files[0];
                var reader = new FileReader();
                reader.onload = (event:any) => {
                    this.Image = event.target.result;
                }
                reader.readAsDataURL(event.target.files[0]);
                this.isBrowser = false;
            } else {
                this.isBrowser = true;
                this._toastr.error("Max image upload size is 500KB only");
            }
        }
    }
    /*end Of On Change profile Image*/


    /*Image api*/
    AddImage(event: any){
        let data=new FormData();
        if(this.file){
            data.append('image',this.file);
            this._db.Post('api/users/image',data).subscribe(b=>{
                if(b.IsResult){
                    this._toastr.success(b.ResultMsg);
                    this.getProfileDetail();
                    this.isBrowser=true;
                }
            });
        }else{
            this._toastr.error("Something went wrong");
        }
    }   

这是从哪里来的?"this.Image" 这个声明在哪里? - Tanwer
声明图像为图像:字符串 = ''; - Suhas Mandumale

1

将图像作为base64读取:

  selectFile(event){
      var files = event.target.files;
      var file = files[0];

    if (files && file) {
        var reader = new FileReader();

        reader.onload =this.handleFile.bind(this);

        reader.readAsBinaryString(file);
    }
  }



  handleFile(event) {
     var binaryString = event.target.result;
            this.base64textString= btoa(binaryString);
            console.log(btoa(binaryString));
    }


***********************************************************************************

或者

备选方案:使用NPM包:

https://www.npmjs.com/package/alife-file-to-base64

安装:npm install alife-file-to-base64 --save

将依赖项添加到您的项目中

将AlifeFileToBase64Module导入到您的项目中,并在导入部分包含该模块

import { AlifeFileToBase64Module } from 'alife-file-to-base64';

@NgModule({
  declarations: [
  ],
  imports: [
    AlifeFileToBase64Module
  ],
  providers: [],
  bootstrap: [AppComponent]
})

在项目中使用的语法:

<input type="file" alife-file-to-base64 (onFileChanged)="onFileChanges($event)" [(fileModel)]="files" />
  • onFileChanged:当用户选择文件时将调用此函数。它将包含文件名、文件大小、类型和base64编码。
  • fileModel:设置组件变量的值。

尝试这个来获取二进制文件。 - Dinesh Ghule
请检查这个答案。 - Dinesh Ghule
我会尝试你的第二个选项,即 NPM 包。 - Tanwer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接