javascript - 使用 Angular 6 上传 JSON 文件
问题描述
我正在尝试使用此方法从用户加载 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
}
}
该行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
文件的内容。它是一个文件对象。要读取 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);
}
}
推荐阅读
- python - 从 API Gateway 获取查询字符串参数
- php - 使用PHP,我如何将一个大整数四舍五入到最接近的百万
- sonarqube - Sonarqube-8.6.1.40680 无法连接到 AWS Aurora Postgresql Serverless
- css - 如何仅在一个实例中更改 SVG 图标的颜色
- python - 如何在 pytorch 模型中保留不用于训练的特征
- python - 如何处理看起来像 Pandas DataFrame 的表的字符串流
- python - 在列表的元素之间搜索等价
- php - 如何使用 PHP 从 json 中回显多个图像
- sql - 为什么我的非零分母在 SQL 中给出“除以零”错误?
- python - 如何将张量列表放入pytorch中的新张量中?