Angular 2 encode image to base64

后端 未结 4 1537
甜味超标
甜味超标 2020-12-24 02:28

I want to encode the uploaded files to base64 so that I can pass them to the request. The problem is that I\'m using Angular 2 with Typescript and I couldn\'t find any info

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-24 02:49

    A possible solution using Rxjs

      import { fromEvent } from 'rxjs';
      import { pluck } from 'rxjs/operators';
    
       onUploadImage(event) {
        if (event.target.files.length > 0) {
          const fileReader = new FileReader();
          let imageToUpload = event.target.files.item(0);
          this.imageToBase64(fileReader, imageToUpload)
            .subscribe(base64image => {
              // do something with base64 image..
            });
        }
      }
    
      imageToBase64(fileReader: FileReader, fileToRead: File): Observable {
        fileReader.readAsDataURL(fileToRead);
        return fromEvent(fileReader, 'load').pipe(pluck('currentTarget', 'result'));
      }
    

提交回复
热议问题