Reputation: 3696
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
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
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