FileUpload.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. path: ''
  20. }
  21. upload = async event => {
  22. event.preventDefault()
  23. const { validity, files } = event.target
  24. const data = new FormData()
  25. data.append('file', files[0])
  26. const res = await fetch(`${endpoint}/upload`, {
  27. method: 'POST',
  28. body: data
  29. })
  30. const { error, file } = await res.json()
  31. if (error) throw new Error('Failed to upload.')
  32. console.log(file)
  33. this.setState({ path: `${endpoint}/${file.path}` })
  34. }
  35. render() {
  36. return (
  37. <form>
  38. <input type='file' name='file' id='file' onChange={this.upload} />
  39. <img src={this.state.path} alt={this.state.name} />
  40. </form>
  41. )
  42. }
  43. }
  44. export default FileUpload