Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ChrisSFR's avatar

VueJS csv Filereader

Hi Folks, 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);
            }
            
        }
    })
0 likes
3 replies
Birozz's avatar

Anyone can help explain the described behavior above ? Thanx :)

ssn's avatar

Hi @chrissfr did you find any solution for this. I have the same situation. I need to upload csv and have to send its content to backend. Didn't find any help on this. All the tutorials out there use image to upload and csv

ChrisSFR's avatar
ChrisSFR
OP
Best Answer
Level 10

@ssn wow Thats a long time ago :D

I posted the same question later to stackoverflow: https://stackoverflow.com/questions/34498596/vuejs-csv-filereader

David K. Rees answered the following:

"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."

Please or to participate in this conversation.