Phi*_*p L 3 html javascript json typescript angular
我正在尝试使用以下方法从用户加载JSON文件:
<input
style="display: none"
type="file" (change)="onFileChanged($event)"
#fileInput>
<button (click)="fileInput.click()">Select File</button>
<button (click)="onUpload()">Upload!</button>
Run Code Online (Sandbox Code Playgroud)
这是组件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
}
}
Run Code Online (Sandbox Code Playgroud)
该行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
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试使用它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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1935 次 |
| 最近记录: |