【问题标题】:Convert a File into base64 file with angular2使用angular2将文件转换为base64文件
【发布时间】:2017-07-23 23:40:48
【问题描述】:

我想使用 Angular2 并使用一个通过 base64 字符串获取文件的 web 服务。

在(成功)通过http获取文件数据后尝试了很多东西。 但是我没有把它变成base64,这非常令人沮丧......如果有人能给我一个有用的提示,那就太好了!

[import {Component, OnInit} from '@angular/core';
import {DemoService} from './demo.service';
import {Observable} from 'rxjs/Rx';
import {Http} from '@angular/http';

@Component({
  selector: 'demo-app',
  template:`
  <h1>Get IP Address online</h1> <br>
  text2 bac  {{orderString}}<br>
  <b>json</b>: {{data}} <br>
  <b>json</b>: {{data2}} <br>
  <b>json</b>: {{data3}} <br>
  `
})


export class AppComponent {

  public order: any;
  public orderString:string;
  public lastname : string;
  public data: any;
  public data2: any;
  public data3: any;


  constructor(private http:Http) {
    console.log('constructor');
    this.orderString = 'TEST';


    var reader: FileReader;

    this.http.get('test.png')
        .subscribe(res => {
          var x: any;
          //this.data = res.blob();
          this.data2 = res.text();
          //this.data3 = btoa(res.arrayBuffer.toString());
          var fileString: string;

          reader = new FileReader();

          reader.onloadend = function() { 
             fileString = reader.result;             
             alert(fileString);
          }
          reader.onload = function() { 
             fileString = reader.result;             
             alert(fileString);
          }

          reader.readAsDataURL(res.blob());
          reader.readAsBinaryString(res.blob());

          this.data3 = fileString;
        });

        //new base64encodeexample().encodeFile('kaikaito-app-icon.png');
  }

  ngOnInit() {
    console.log('ngOnInit');
    this.orderString = 'TEST';
  }
}][1]

【问题讨论】:

    标签: angular file get base64


    【解决方案1】:
    import { Observable, Observer } from "rxjs";
    convertFileToDataURLviaFileReader(url: string) {
     Observable.create((observer: Observer) => {
      let xhr: XMLHttpRequest = new XMLHttpRequest();
      xhr.onload = function() {
       let reader: FileReader = new FileReader();
       reader.onloadend = function() {
        observer.next(reader.result);
        observer.complete();
       }
       reader.readAsDataURL(xhr.response);
      };
      xhr.open('GET', url);
      xhr.responseType = 'blob';
      xhr.send();
     });
    }
    

    像这样调用方法

    convertFileToDataURLviaFileReader(`xyz.com/a.png`).subscribe(base64 => {
     console.log(base64);
    });
    

    演示:http://jsfiddle.net/handtrix/YvQ5y/

    您可以将其包装在 observable 中或根据您的文件对其进行自定义

    【讨论】:

    • 感谢您的 sn-p。我也可以通过 TypScript 做到这一点,因为它看起来像 JavaScript Snippet...
    猜你喜欢
    • 2017-09-25
    • 2015-09-18
    • 1970-01-01
    • 2015-04-29
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多