Get file object from file Input
The ref string attribute is considered legacy, and will most likely be deprecated at some point in the future. The way to do this now is with a callback ref. Below I demonstrate using an ES6 arrow function.
Change your input element to:
<Input
type='file' label='Upload' accept='.txt'
buttonAfter={uploadFileButton}
ref={(ref) => this.fileUpload = ref}
/>
Then you can use:
const file = this.fileUpload.files[0];
And so on.
It's pretty straight forward; I completely missed this:
var files = this.refs.fileUpload.getInputDOMNode().files;
The more current version of this would be something like:
function MyComponent(): JSX.Element {
const handleFileSelected = (e: React.ChangeEvent<HTMLInputElement>): void => {
const files = Array.from(e.target.files)
console.log("files:", files)
}
return (
<input onChange={handleFileSelected} type="file" />
)
}
The attribute is found on e.target.files
which you can get from the onChange
event.
EDIT: Removed unnecessary ref code, hat tip Mark in comments ð
I solved file upload like this for React-Bootstrap
with a custom looking button:
addFile = (event: any): void => {
console.log(event.target.files[0]);
}
<FormGroup>
<ControlLabel htmlFor="fileUpload" style={{ cursor: "pointer" }}><h3><Label bsStyle="success">Add file</Label></h3>
<FormControl
id="fileUpload"
type="file"
accept=".pdf"
onChange={this.addFile}
style={{ display: "none" }}
/>
</ControlLabel>
</FormGroup>