0

I have created a Webapp where the user can upload a json. Afterwards it should print out the content of the json. Unfortunately i receive always an empty array.

Here is my JSON:

"06" : {
    "fallbackLabel" : "Adelholzener Gastro Classic mit Gas",
    "price"         : "0.30",
    "name"          : "0,25l"
},
"07" : {
    "fallbackLabel" : "Adelholzener Gastro Classic ohne Kohlensäure",
    "price"         : "0.30",
    "name"          : "0,25l"
}

and here is my code:

onFileSelected(event){
   this.selectedFile = event.target.files[0];
   this.http.get(this.selectedFile).subscribe(data => {
     console.log(this.selectedFile.text());
   })  
}
Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35
Dominik
  • 143
  • 1
  • 1
  • 7
  • 1
    Do you try upload file with `get()`? If so, I strongly suggest you to check [these docs](https://angular.io/guide/http) to get more familiar with Angular's `HttpClient`. – Harun Yilmaz Jun 14 '19 at 09:11
  • im using get () in my onFileSelected method as you can see this.https.get(this.selectedFile)... – Dominik Jun 14 '19 at 09:21
  • Are you merely trying to print the content of your file? – wentjun Jun 14 '19 at 09:22
  • Then perhaps you could use [this thread](https://stackoverflow.com/a/47581753/1331040) to read content of input file – Harun Yilmaz Jun 14 '19 at 09:26

1 Answers1

1

HttpClient only works with urls : you can't pass a file to the get method (https://angular.io/api/common/http/HttpClient#get).

You must 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));
  }
}
Gérôme Grignon
  • 3,859
  • 1
  • 6
  • 18