Ryan King
Ryan King

Reputation: 3696

ReactJS Ajax File Upload

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>

Upvotes: 1

Views: 6055

Answers (2)

Ryan King
Ryan King

Reputation: 3696

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!");
            });
        },

Upvotes: 2

jackypan1989
jackypan1989

Reputation: 2866

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

Upvotes: 1

Related Questions