1

I'm trying to upload a file with React but am unsure of the best way to do so. I'm trying to store the file on change but that doesn't appear to be working. I'm currently getting the error Uncaught TypeError: Illegal invocation on submit.

Is there a better approach to uploading files with React?


File change & upload functions:

changeFile: function(e) {
            this.setState({csvFile: e.target.files[0]});
        },

importFile: function() {
            data = new FormData();
            data.append('file', this.state.csvFile);
            $.ajax({
                type: "POST",
                url: "/csv/import",
                data: data,
                dataType: "JSON"
            }).done(function(json){
                alert("hooray!");
            });
        },

JSX:

    <div>
        <input type="file" onChange={this.changeFile}/>
        <button onClick={this.importFile}>Import</button>
    </div>
1

2 Answers 2

2

Ugh, turns out I just needed to add the following to my ajax call:

processData: false,
contentType: false

OR

importFile: function() {
            data = new FormData();
            data.append('file', this.state.csvFile);
            $.ajax({
                type: "POST",
                url: "/csv/import",
                data: data,
                dataType: "JSON",
                processData: false,
                contentType: false
            }).done(function(json){
                alert("hooray!");
            });
        },
Sign up to request clarification or add additional context in comments.

Comments

1

The setState is an async function, so you cant get state immediately.
You can try with callback to check your file.

this.setState({
  ...
}, function(){
  ...
  console.log(...);
});

ref: https://facebook.github.io/react/docs/component-api.html#setstate

2 Comments

Thanks, but this creates a new problem on submit: Uncaught TypeError: Illegal invocation
It's a jQuery error. use formdata or jQuery config. see stackoverflow.com/questions/12755945/…

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.