文件读取器 Angular 2
FileReader Angular 2
我正在尝试在 组件 A 中上传图像,并将上传图像的 base 64 数据发送到 组件 B。我在 组件 A
中遇到问题
HTML:
<input type="file" id="hotspot" (change)="uploadHotSpot($event)">
TS 文件:
uploadHotSpot($event){
var file:File = $event.target.files[0];
var reader:FileReader = new FileReader();
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
this.pin = reader.result;
console.log(this.pin);
}
}
问题: 当我上传图像并保持开发者工具打开时,我能够在控制台日志中获取 base 64 数据,但是当调试器工具关闭时我试图上传我得到的图像 console.log 为空白.....有什么想法吗?
因为这就是现在的运作方式。您应该创建一个 onload
回调来获取结果。像这样:
uploadHotSpot($event) {
var file:File = $event.target.files[0];
var reader:FileReader = new FileReader();
reader.onload = () => {
this.pin = reader.result;
console.log(this.pin);
};
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
}
}
我正在尝试在 组件 A 中上传图像,并将上传图像的 base 64 数据发送到 组件 B。我在 组件 A
中遇到问题HTML:
<input type="file" id="hotspot" (change)="uploadHotSpot($event)">
TS 文件:
uploadHotSpot($event){
var file:File = $event.target.files[0];
var reader:FileReader = new FileReader();
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
this.pin = reader.result;
console.log(this.pin);
}
}
问题: 当我上传图像并保持开发者工具打开时,我能够在控制台日志中获取 base 64 数据,但是当调试器工具关闭时我试图上传我得到的图像 console.log 为空白.....有什么想法吗?
因为这就是现在的运作方式。您应该创建一个 onload
回调来获取结果。像这样:
uploadHotSpot($event) {
var file:File = $event.target.files[0];
var reader:FileReader = new FileReader();
reader.onload = () => {
this.pin = reader.result;
console.log(this.pin);
};
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
}
}