1

So I am trying to store JSON data in a variable in a Vue project.

The code to upload and store the file is

<input type="file" id="file" ref="fileSelect" class="custom-file-input" @change="showfiles" />

<script lang="ts">
.
.
methods: {
showfiles() {
    let files = this.$refs.fileSelect.files //Error Object is of type 'unknown'. ts(2571) 
    var reader = new FileReader();
    reader.onload = ({ target: { result }}) => { this.p = JSON.parse(result); };
    reader.readAsText(files[0]);
    console.log(this.p) //I am storing JSON data in p
}}

I searched online and found various fixes but none of them are working for me I tried adding "useUnknownInCatchVariables": false to tsconfig, it fixes the error momentarily but the error comes back. I also tried try and catch

showfiles() {
      try{
        let files = this.$refs.fileSelect.files
        var reader = new FileReader();
        reader.onload = ({ target: { result }}) => { this.p = JSON.parse(result); };
        reader.readAsText(files[0]);
        console.log(this.p)
      }
      catch(err) {
        if (err instanceof Error) { 
      console.log(err.message);
    } else {
      console.log('Unexpected error', err);
    }
}
    }

But none of these worked. I'll greatly appreciate any suggestion.

1
  • You didn't type fileSelect ref Commented Jun 2, 2022 at 6:22

1 Answer 1

1

Try to cast the type of fileSelect ref yourself like that:

showfiles() {
  const files = (this.$refs.fileSelect as HTMLInputElement).files // const files: FileList | null
    // ...
  }

I guess you are not reading the result correctly. According to MDN you should just take the result from filereader's result property.

reader.addEventListener("load", () => {
  this.p = JSON.parse(reader.result);
}, false);

Sign up to request clarification or add additional context in comments.

7 Comments

Now I am getting an error in the next lines reader.onload = ({ target: { result }}) => { this.p = JSON.parse(result); }; Property 'result' does not exist on type 'FileReader | null'.ts(2339) and in line reader.readAsText(files[0]); Object is possibly 'null'.ts(2531)
That was not clear from your question.
Try to access the result like that: reader.onload = () => { this.p = JSON.parse(reader.result); }
I wasn't getting these errors before, I got them after I cast the type of fileSelect.
And also why are you using filereader's readAsText method instead of readAsDataURL ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.