[英]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.