FileUpload.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { endpoint } from '../config'
  2. class FileUpload extends React.Component {
  3. state = {
  4. file: null,
  5. description: '',
  6. path: '',
  7. uploading: false
  8. }
  9. upload = async event => {
  10. event.preventDefault()
  11. if (!this.state.file) {
  12. alert('Please select file first.')
  13. return
  14. }
  15. this.setState({ uploading: true })
  16. const data = new FormData()
  17. data.append('file', this.state.file)
  18. data.append('description', this.state.description)
  19. const res = await fetch(`${endpoint}/upload`, {
  20. method: 'POST',
  21. body: data
  22. })
  23. const { error, file } = await res.json()
  24. if (error) {
  25. console.error(error)
  26. alert('Upload error.')
  27. this.setState({ uploading: false })
  28. }
  29. this.setState({ path: `${endpoint}/${file.path}`, uploading: false })
  30. }
  31. selectFile = event => {
  32. const { validity, files } = event.target
  33. this.setState({ file: files[0] })
  34. }
  35. handleChange = event => {
  36. this.setState({ [event.target.name]: event.target.value })
  37. }
  38. render() {
  39. return (
  40. <form>
  41. <fieldset>
  42. <input type='file' name='file' id='file'
  43. onChange={this.selectFile}
  44. />
  45. <textarea name="description" id="description" placeholder="Description"
  46. value={this.state.description}
  47. onChange={this.handleChange}
  48. ></textarea>
  49. <img src={this.state.path} alt={this.state.name} />
  50. <button onClick={this.upload} disabled={this.state.uploading}>Save</button>
  51. </fieldset>
  52. </form>
  53. )
  54. }
  55. }
  56. export default FileUpload