Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
65
rated 0 times [  69] [ 4]  / answers: 1 / hits: 22813  / 9 Years ago, mon, december 28, 2015, 12:00:00

I'm trying to get the input of a .csv File, after I choose it with my Html 5 input field. Therefor I use a onFileChange method and a FileReader().
Here is an example I used: http://codepen.io/Atinux/pen/qOvawK/ (except that I want to read the text input, and not an image file).



My Problem is, that I get an empty input on the first try, but on the second try it works. Why is that? Any ideas? (I'm a javascript beginner ;) )



html:



<form enctype=multipart/form-data>
<input type=file @change=onFileChange>
</form>


js:



new Vue({
el: '#app',
data: {
fileinput: ''
},
methods: {
onFileChange(e) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.createInput(files[0]);
},
createInput(file) {
var reader = new FileReader();
var vm = this;
reader.onload = (e) => {

vm.fileinput = reader.result;
}
reader.readAsText(file);

console.log(this.fileinput);
}

}
})

More From » vue.js

 Answers
35

The reason why the console.log is not displaying anything is because FileReader.readAsText() is asynchronous. It completes after the console.log has executed.



You can typically deal with this by putting a watch on fileInput or throwing a local event using vm.$emit from the onload handler.


[#63919] Friday, December 25, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
joanneamiyaa

Total Points: 532
Total Questions: 127
Total Answers: 98

Location: Guam
Member since Tue, Nov 3, 2020
4 Years ago
joanneamiyaa questions
Thu, Apr 30, 20, 00:00, 4 Years ago
Thu, Feb 20, 20, 00:00, 4 Years ago
Mon, Oct 14, 19, 00:00, 5 Years ago
;