我想利用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]
答案 0 :(得分: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/
您可以将其包装在可观察的内容中,或者根据您的文件对其进行自定义