I have been working on uploading and saving multiple JSON files. In the past, I had successfully implemented code for uploading and saving a single JSON file using the following approach:
<input type="file" id="file" ref="fileSelect" class="custom-file-input" @change="showfiles" />
showfiles() {
let files = (this.$refs.fileSelect as HTMLInputElement).files
var reader = new FileReader();
reader.onload = () => { this.data = JSON.parse(reader.result as string); }
reader.readAsText(files![0]);
}
I used to save the JSON file data in this.data
.
Now, my goal is to upload and save multiple JSON files in a similar manner and store them in this.data
. So, I made some updates to the existing code thinking that I could loop through and append the file data:
<input multiple type="file" id="file" ref="fileSelect" class="custom-file-input" @change="showfiles" />
showfiles() {
let files = (this.$refs.fileSelect as HTMLInputElement).files
for(let i=0;i<files!.length;i++){
var reader = new FileReader();
reader.onload = () => { this.data[i] = JSON.parse(reader.result as string); }
reader.readAsText(files![i]);}
}
However, this updated code is not functioning as expected. It seems to be appending only the last selected file multiple times (with the 0th index being null). For instance, if I select file1.json
, file2.json
, file3.json
, then in this.data
- 0 is null
and indexes 1 and 2
contain the data from file3.json
.
What might I be doing wrong?
Here is my current complete code:
<input multiple type="file" id="file" ref="fileSelect" class="custom-file-input" @change="showfiles" />
<script lang='ts'>
import { defineComponent } from "vue"
export default defineComponent({
name: 'HomeView',
props: [],
data(){
return{
data:{}
};
},
methods: {
showfiles() {
this.data={}
let files = (this.$refs.fileSelect as HTMLInputElement).files
for(let i=0;i<files!.length;i++){
var reader = new FileReader();
reader.onload = () => { this.data[i] = JSON.parse(reader.result as string);}
reader.readAsText(files![i]);
}
}