Upload.tsx 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * <<
  3. * Davinci
  4. * ==
  5. * Copyright (C) 2016 - 2017 EDP
  6. * ==
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. * >>
  19. */
  20. import React, {
  21. useCallback,
  22. useState,
  23. RefForwardingComponent,
  24. PropsWithChildren
  25. } from 'react'
  26. import { Upload as AntUpload, Spin } from 'antd'
  27. import { UploadChangeParam } from 'antd/lib/upload'
  28. interface IUploadProps {
  29. name: string
  30. action: string
  31. onChange?: (path: string) => void
  32. }
  33. const Upload: RefForwardingComponent<
  34. AntUpload,
  35. PropsWithChildren<IUploadProps>
  36. > = (props, ref) => {
  37. const { name, action, onChange } = props
  38. const [loading, setLoading] = useState(false)
  39. const headers = {
  40. authorization: `${localStorage.getItem('TOKEN')}`
  41. }
  42. const change = useCallback((info: UploadChangeParam) => {
  43. const { status, response } = info.file
  44. if (status === 'uploading') {
  45. setLoading(true)
  46. return
  47. }
  48. if (status === 'done') {
  49. onChange(response.payload)
  50. }
  51. setLoading(false)
  52. }, [])
  53. return (
  54. <AntUpload
  55. ref={ref}
  56. showUploadList={false}
  57. name={name}
  58. action={action}
  59. headers={headers}
  60. onChange={change}
  61. >
  62. {loading ? <Spin /> : props.children}
  63. </AntUpload>
  64. )
  65. }
  66. export default React.forwardRef(Upload)