1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- import { endpoint } from '../config'
- class FileUpload extends React.Component {
- state = {
- file: null,
- description: '',
- path: '',
- uploading: false
- }
- upload = async event => {
- event.preventDefault()
- if (!this.state.file) {
- alert('Please select file first.')
- return
- }
- this.setState({ uploading: true })
- const data = new FormData()
- data.append('file', this.state.file)
- data.append('description', this.state.description)
- const res = await fetch(`${endpoint}/upload`, {
- method: 'POST',
- body: data
- })
- const { error, file } = await res.json()
- if (error) {
- console.error(error)
- alert('Upload error.')
- this.setState({ uploading: false })
- }
- this.setState({ path: `${endpoint}/${file.path}`, uploading: false })
- }
- selectFile = event => {
- const { validity, files } = event.target
- this.setState({ file: files[0] })
- }
- handleChange = event => {
- this.setState({ [event.target.name]: event.target.value })
- }
- render() {
- return (
- <form>
- <fieldset>
- <input type='file' name='file' id='file'
- onChange={this.selectFile}
- />
- <textarea name="description" id="description" placeholder="Description"
- value={this.state.description}
- onChange={this.handleChange}
- ></textarea>
- <img src={this.state.path} alt={this.state.name} />
- <button onClick={this.upload} disabled={this.state.uploading}>Save</button>
- </fieldset>
- </form>
- )
- }
- }
- export default FileUpload
|