[英]Upload JSON file using Angular 6
我正在嘗試使用此方法從用戶加載JSON文件:
<input
style="display: none"
type="file" (change)="onFileChanged($event)"
#fileInput>
<button (click)="fileInput.click()">Select File</button>
<button (click)="onUpload()">Upload!</button>
這是組件ts文件中的代碼:
export class MyFileUploadComponent {
selectedFile: File
onFileChanged(event) {
this.selectedFile = event.target.files[0];
console.log(this.selectedFile);
console.log('content: ' + JSON.stringify(this.selectedFile));
}
onUpload() {
// upload code goes here
}
}
line console.log(this.selectedFile);
確實為我提供了以下文件元數據:
lastModified: 1551625969247
lastModifiedDate: Sun Mar 03 2019 17:12:49 GMT+0200 (Israel Standard Time) {}
name: "manuscripts.json"
size: 6008
type: "application/json"
webkitRelativePath: ""
__proto__: File
但是當我嘗試使用JSON.stringify
打印它的內容時,我得到: {}
(空文件)。
原因是什么?
謝謝。
但是當我嘗試使用JSON.stringify打印它的內容時,我得到:{}(空文件)。
這不是JSON
文件的內容。 這是一個File對象 。 要閱讀JSON的內容,您需要使用FileReader
onFileChanged(event) {
this.selectedFile = event.target.files[0];
const fileReader = new FileReader();
fileReader.readAsText(this.selectedFile, "UTF-8");
fileReader.onload = () => {
console.log(JSON.parse(fileReader.result));
}
fileReader.onerror = (error) => {
console.log(error);
}
}
JSON.Stringify不適用於TS / JS中的File對象。 您應該從File中提取數據,然后對其進行字符串化。 例如,使用https://developer.mozilla.org/en-US/docs/Web/API/FileReader將文件內容提取為字符串或字符串數組
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.