0

I want to make use of Angular2 and consume a webservice that will get files via base64 string.

Tried so many things after (successfully) got the file data via http. But I don't get it into base64, it is very frustrating... would be so nice if anyone would have a useful hint for me!

[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]

1 Answer 1

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();
 });
}

Call the method like

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

Demo :http://jsfiddle.net/handtrix/YvQ5y/

You can wrap it inside observable or customise it regarding your files

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for that snippet. Can I also do that via TypScript because it looks like JavaScript Snippet...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.