FileUpload.js 1.1 KB

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