[英]How to get results of File reader
所以我的 html 中有一個 onchange 事件,它從用戶那里獲取圖像,需要將其轉換為數據 url 以便通過 socket.io 發送並存儲在數據庫中。 如何獲得文件閱讀器 object 的結果。 我不知道如何傳入回調
我需要做的是將 function 回調到文件讀取器 onload 事件中,以便我可以將圖片變量設置為數據 url 然后通過套接字發送。 只需要幫助從文件閱讀器獲取結果到我的全局變量// HTML
<input type = 'file' (change) = "setpreview($event)" value = 'upload photo'>
// js代碼。
setpreview(event) {
var img = <File>event.target.files[0];
var reader = new FileReader();
reader.onload = function() {
console.log(reader.result);
}
reader.readAsDataURL(img);
}
你得到它只是將結果分配給一個作用域變量並在模板中使用它
srcImg = null; //declare this
setpreview(event) {
const comp = this;
const img = <File>event.target.files[0];
const promise = new Promise((resolve) => {
const reader = new FileReader();
reader.onload = function () {
resolve(reader.result);
}
reader.readAsDataURL(img);
});
promise.then(img => {
comp.srcImg = img;
// if you want to do anything with img you can do it here
});
}
<input type = 'file' (change) = "setpreview($event)" value = 'upload photo'>
<img [src]="srcImg" *ngIf="srcImg" />
更新 Stackblitz: https://stackblitz.com/edit/angular-tkbbdh
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.