7

我正在使用 ReactJS 开发项目,目前我正在使用 ant-design 进行文件上传。我想在用户选择视频时预览视频。我是 reactjs 新手,无法完成我的任务。有人可以帮助我如何预览视频。我将与您分享我的代码您可以检查我的代码。谢谢

代码

import React from 'react';
import styled from 'styled-components';
import 'antd/dist/antd.css';
import './styletwo.css';
import { Form, Upload, Button, Icon } from 'antd';
// import reqwest from 'reqwest';
const Dragger = Upload.Dragger;

const FormItem = Form.Item;
const PhotoText = styled.div`
  font-size: 16px;
  font-weight: bold;
  padding: 2rem 0 1rem 0;
  display: block;
  text-align: -webkit-auto;
`;

const props = {
  action: '',
  listType: 'picture',
};
class RegisterStepTwo extends React.Component {


  render() {

    const { getFieldDecorator } = this.props;

    return (
      <div>
        <PhotoText>Select a Photo to Upload</PhotoText>
          <FormItem>
            {getFieldDecorator('picture', {
              rules: [
                {
                  required: true,
                  message: 'Please upload picture!',
                },
              ],
            })(
              <Dragger {...props}>
                <p className="ant-upload-drag-icon">
                  <Icon type="upload" />
                </p>
                <p className="ant-upload-text">
                  Click or drag photo to this area to upload
                </p>
              </Dragger>,
            )}
          </FormItem>

          <PhotoText>Select a Video to Upload</PhotoText>
          <FormItem>
            {getFieldDecorator('video', {
              rules: [
                {
                  required: true,
                  message: 'Please upload video!',
                },
              ],
            })(
              <Dragger>
              <p className="ant-upload-drag-icon">
                <Icon type="upload" />
              </p>
              <p className="ant-upload-text">
                Click or drag Video to this area to upload
              </p>
            </Dragger>,
            )}
          </FormItem>

      </div>
    );
  }
}
export default RegisterStepTwo;
4

2 回答 2

5

考虑到您的视频文件处于以下状态:

    const [videoFile, setVideoFile] = useState();

您可以createObjectUrl直接在 JSX 中使用:

<video width="400" controls>
    <source src={URL.createObjectURL(videoFile)}/>
</video>
于 2020-11-02T18:37:37.807 回答
1

首先从文件中读取 blob 数据

let reader = new FileReader();

//if reading completed
reader.onload = e => {
     let blobData = e.target.result); //blob data
     console.log(blobData);
};

//read the file
reader.readAsDataURL(file);

读取为 blob 后,您可以使用 html5 视频标签来显示视频,如下所示

<video width="400" controls>
     <source src={blobData} type={fileType}/>
     Your browser does not support HTML5 video.
</video>

请看看我的粗略 CodeSandBox https://codesandbox.io/s/wq2jnm9wpk

我希望这会对你有所帮助。

于 2019-04-30T10:46:28.070 回答