FileUpload.js 2.4 KB

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