我想從檔案系統中讀取一個 JSON 檔案,但我無法讓它作業。
我發現這個解決方案似乎是我需要的:是否可以通過檔案上傳來上傳 JSON 檔案并在 Angular 6 中讀取內容而無需與 API 交談?
但我得到兩個錯誤:
引數“事件”隱式具有“任何”型別 uploadFile(event) {
和
物件可能在console.log(reader.result.toString());
這是我的代碼:
組件.html:
<form name="JSONform" (ngSubmit)="fJSON.form.valid && decryptJSON()" #fJSON="ngForm" novalidate>
<input type="file" name="files" (change)="uploadFile($event)" />
<div class="buttons">
<div class="decrypt">
<button class="btn btn-primary" type="submit">Decrypt</button>
</div>
</div>
</form>
組件.ts:
uploadFile(event) {
if (event.target.files.length !== 1) {
console.error('No file selected');
} else {
const reader = new FileReader();
reader.onloadend = (e) => {
console.log(reader.result.toString());
// handle data processing
};
reader.readAsText(event.target.files[0]);
}
}
我不知道我錯過了什么。先感謝您。
uj5u.com熱心網友回復:
你沒有錯過任何東西。這些錯誤是 TSLINT 或 TypeScript 錯誤。只需檢查它們:
// Tell TS that you mean it as any (or you can find the actual event d.ts
// Use the ? operator to check for nulls (or do an if( reader.result != null)
// before calling toString()
uploadFile(event: any) {
if (event.target.files.length !== 1) {
console.error('No file selected');
} else {
const reader = new FileReader();
reader.onloadend = (e) => {
console.log(reader.result?.toString());
// handle data processing
};
reader.readAsText(event.target.files[0]);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/426776.html
