I am using the <p-fileUpload>
from PrimeNG to upload a json file in my web-app. I want to read the json file, in the front-end, and change some values of a data table.
However, I have no idea how to parse the uploaded file as a json to a typescript object. Any ideas?
In the HTML file:
<p-fileUpload #ratingsUpload mode="basic" name="demo[]"
url="" accept=".json"
styleClass="p-button-raised"
[auto]="true" chooseLabel="Upload ratings"
(onUpload)="onRatingsUpload($event)"></p-fileUpload>
In the typescript file:
onRatingsUpload(event: any) {
console.log(event.files)
// TODO:
// data = JSON(event.files);
}
Edit: I can't get the event to fire. onRatingsUpload does not seem to be called...
You have to use FileReader:
const reader = new FileReader();
reader.onload = (event) => {
try {
var obj = JSON.parse((event.target.result) as string);
console.log('my json:', obj);
} catch (error) {
console.error(error);
}
};
reader.readAsText(file);
//You need to use 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); } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.