我使用此鏈接將影像轉換為 Angular 中的位元組陣列
在Angular(打字稿)中將影像轉換為位元組陣列
但 src 未系結到影像以進行預覽我的打字稿代碼是:
upload() : void {
const file = (document.querySelector('input[type=file]') as HTMLInputElement).files![0];
const preview = document.getElementById('preview') as HTMLImageElement;
const reader = new FileReader();
let byteArray;
reader.addEventListener("loadend", function () {
// convert image file to base64 string
console.log('base64', reader.result);
**preview.src != reader.result;**
byteArray = convertDataURIToBinary(reader.result);
console.log('byte array', byteArray);
}, false);
if (file) {
reader!.readAsDataURL(file);
}
}
}
function convertDataURIToBinary(dataURI:any) {
var base64Index = dataURI.indexOf(';base64,') ';base64,'.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for(let i = 0; i < rawLength; i ) {
array[i] = raw.charCodeAt(i);
}
return array;
}
我的html是
<input type="file" id="file" accept="image/*" width="300" height="300" />
<button (click)="upload()">Upload</button>
<img id="preview">
我的問題是 src 為空且未顯示影像的這一行
謝謝
uj5u.com熱心網友回復:
請將閱讀器結果保存到變數中,并使用與 HTML 中 img 標簽的源相同的內容
TS 檔案:
binaryImage : any;
...
this.binaryImage = reader.result;
...
HTML 檔案:
<img src="{{binaryImage}}">
或者
<div style="background-image: url({{binaryImage}});">
uj5u.com熱心網友回復:
你不應該從你的打字稿中“定位”元素,而是使用資料系結方法,這是 Angular 中的首選方法。
在您的 HTML 中:
<img src="{{previewImage}}" *ngIf="previewImage">
在您的打字稿中更新以下代碼段:
reader.addEventListener("loadend", function () {
// convert image file to base64 string
console.log('base64', reader.result);
**preview.src != reader.result;**
...
進入這個:
reader.addEventListener("loadend", () => {
// convert image file to base64 string
console.log('base64', reader.result);
this.previewImage = reader.result;
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/481026.html
上一篇:型別'JQueryPromise<unknown>'不可分配給型別'JQueryPromise<string>'
