AliyunOssUploader.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import React from 'react';
  2. import { Upload, message, Button } from 'antd';
  3. class AliyunOSSUpload extends React.Component {
  4. state = {
  5. OSSData: {},
  6. };
  7. componentDidMount() {
  8. this.init();
  9. }
  10. init = () => {
  11. try {
  12. const { OSSData } = this.props;
  13. this.setState({
  14. OSSData,
  15. });
  16. } catch (error) {
  17. message.error(error);
  18. }
  19. };
  20. onChange = ({ file, fileList }) => {
  21. const { onChange, onDone, onUploading } = this.props;
  22. console.log('Aliyun OSS:', file, fileList);
  23. if (onChange) {
  24. onChange([...fileList]);
  25. }
  26. if (onDone) {
  27. if (file.status === 'done') onDone(file);
  28. }
  29. if (onUploading && file.status === 'uploading') {
  30. onUploading({ file, fileList });
  31. }
  32. this.setState({ fileList: [...fileList] });
  33. };
  34. onRemove = file => {
  35. const { value, onChange } = this.props;
  36. const files = value.filter(v => v.url !== file.url);
  37. if (onChange) {
  38. onChange(files);
  39. }
  40. };
  41. transformFile = file => {
  42. const { OSSData } = this.state;
  43. file.url = OSSData.dir + '/' + file.name;
  44. return file;
  45. };
  46. getExtraData = file => {
  47. const { OSSData } = this.state;
  48. return {
  49. key: file.url,
  50. OSSAccessKeyId: OSSData.accessid,
  51. policy: OSSData.policy,
  52. Signature: OSSData.signature,
  53. };
  54. };
  55. beforeUpload = async file => {
  56. const { OSSData } = this.state;
  57. const expire = OSSData.expire * 1000;
  58. file.url = OSSData.dir + '/' + file.name;
  59. console.log(file);
  60. if (expire < Date.now()) {
  61. await this.init();
  62. }
  63. if (this.props.beforeUpload) {
  64. return this.props.beforeUpload(file);
  65. }
  66. return true;
  67. };
  68. render() {
  69. const { value, directory, label, noStyle, showUploadList, accept } = this.props;
  70. const props = {
  71. name: 'file',
  72. fileList: this.state.fileList,
  73. action: this.state.OSSData.host,
  74. onChange: this.onChange,
  75. onRemove: this.onRemove,
  76. transformFile: this.transformFile,
  77. data: this.getExtraData,
  78. beforeUpload: this.beforeUpload,
  79. accept: accept,
  80. showUploadList: showUploadList !== false,
  81. headers: { 'Access-Control-Allow-Origin': '*' },
  82. };
  83. return (
  84. <Upload {...props} directory={directory}>
  85. {noStyle ? label : <Button type="primary">{label}</Button>}
  86. </Upload>
  87. );
  88. }
  89. }
  90. export default AliyunOSSUpload;