FileUpload.js 1.8 KB

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