UploadVideo.jsx 2.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import React, { useState, useRef } from 'react';
  2. import { Button } from 'antd'
  3. import Upload from './Upload';
  4. import { uplodeNoteImage } from '@/services/note'
  5. import styles from './style.less';
  6. import { useEffect } from 'react';
  7. function beforeUpload(file) {
  8. const isMp4 = file.type === 'video/mp4';
  9. if (!isMp4) {
  10. message.error('请上传 MP4 视频!');
  11. }
  12. return isMp4;
  13. }
  14. export default (props) => {
  15. //onPoster 改变主图事件 isScreenshot判断父组件是否需要截屏按钮
  16. const { value, onChange, onPoster, isScreenshot } = props;
  17. const [loading, setLoading] = useState(false);//上传按钮loading框
  18. const [capturing, setCapturing] = useState(false);//截屏按钮loading框
  19. const [video, setVideo] = useState()//当前上传的视频
  20. const [isVideoReady, setIsVideoReady] = useState(false)//判断视频是否加载成功
  21. const canvasRef = useRef()
  22. const videoRef = useRef()
  23. useEffect(() => {
  24. setVideo(value)//父组件的视频获取成功时改变当前页面的视频
  25. }, [value])
  26. const handleChange = info => {
  27. if (info.file.status === 'uploading') {
  28. setLoading(true);
  29. return;
  30. }
  31. if (info.file.status === 'error') {
  32. setLoading(false);
  33. return;
  34. }
  35. if (info.file.status === 'done') {
  36. onChange(info.file.response);
  37. setLoading(false);
  38. }
  39. };
  40. //开始截图
  41. const handelScreenshot = () => {
  42. const ctx = canvasRef.current.getContext("2d");
  43. ctx.drawImage(videoRef.current, 0, 0);
  44. const image = canvasRef.current.toDataURL("image/png", 0.9)
  45. setCapturing(true)
  46. uplodeNoteImage({ base64: image }).then((res) => {
  47. onPoster(res)
  48. setCapturing(false)
  49. })
  50. }
  51. //视频加载成功事件
  52. const handleVideoReady = (e) => {
  53. setIsVideoReady(true)
  54. canvasRef.current.width = e.target.videoWidth;
  55. canvasRef.current.height = e.target.videoHeight;
  56. }
  57. return (
  58. <div className={styles['video-uploader']}>
  59. <Upload
  60. className="image-uploader"
  61. showUploadList={false}
  62. beforeUpload={beforeUpload}
  63. onChange={handleChange}
  64. >
  65. <div style={{ maxWidth: '1px', maxHeight: '1px', overflow: 'hidden' }}>
  66. <canvas ref={canvasRef}></canvas>
  67. </div>
  68. <Button loading={loading}>
  69. 点击上传视频 (MP4)
  70. </Button>
  71. </Upload>
  72. {
  73. isScreenshot && (
  74. // disabled={!isVideoReady} 当视频准备成功时截屏按钮可以点击 否则不能点击
  75. <Button loading={capturing} style={{ marginLeft: '1em' }} onClick={handelScreenshot} disabled={!isVideoReady}>截屏</Button>
  76. )
  77. }
  78. {
  79. !!video && (
  80. <video ref={videoRef} width="320" height='500' crossOrigin='anonymous' controls src={video} onCanPlay={handleVideoReady}></video>
  81. )
  82. }
  83. </div>
  84. );
  85. }