问题
I'm trying to use a react-bootstrap file input with jquery fileupload()
. With straight jquery I would do $('#fileUpload').prop('files')
to get the files to pass to the fileupload call. However, I don't know how to get the files correctly with react-bootstrap.
<Input type='file' label='Upload' accept='.txt' ref='fileUpload' buttonAfter={uploadFileButton}/>
回答1:
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.
回答2:
It's pretty straight forward; I completely missed this:
var files = this.refs.fileUpload.getInputDOMNode().files;
回答3:
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>
回答4:
Adding to fahad's answer, if you can't use an arrow function (due to older browser support, or for some other reason), you must bind the React context to the function.
<Input type='file' label='Upload' accept='.txt'
buttonAfter={uploadFileButton}
ref={ function(ref) { this.fileUpload = ref }.bind(this) }
/>
回答5:
This worked for me.
let file = this.refs.fileUpload.files[0];
回答6:
You can access the file object by binding an event handler to the onChange event of the HTML file input.
Here is a quick example using a functional component:
import React from 'react'
function UploadForm(props) {
return(
<div>
<input type="file" name="docx" onChange={setFile.bind(this)} />
<input type="button" onClick={postFile} value="Upload" />
</div>
)
function postFile(event) {
// HTTP POST
}
function setFile(event) {
// Get the details of the files
console.log(event.target.files)
}
}
export default UploadForm;
来源:https://stackoverflow.com/questions/30483645/get-file-object-from-file-input