首页 > 其他分享 >react 表单之upload上传 校验

react 表单之upload上传 校验

时间:2023-01-09 16:46:57浏览次数:43  
标签:info const log .. upload 表单 react file console

import * as React from 'react';
import styles from './VideoEdit.module.scss';
import { IVideoEditProps } from './IVideoEditProps';
import { Button, Form, Input, message, Upload } from 'antd';
import "../../../utils/antdConfig"
import Loading from '../../../components/Loading';
import 'react-quill/dist/quill.snow.css';
import { goToUrl, getLang } from '../../../utils'
// import Upload from '../../../components/Upload';
import type { UploadProps } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
const { useState, useEffect, useRef } = React;

const VideoEdit = (props: IVideoEditProps) => {
  const [loading, setLoading] = useState<boolean>(false)
  const [loadingTxt, setLoadingTxt] = useState<string>(null)
  // const [indicators, setIndicators] = useState<any>({})
  const lang = getLang()
  const [form] = Form.useForm();
  const { api } = props;
  const onFinish = () => {
    form.validateFields().then((values) => {
      values.CoverImgFile = values.CoverImgFile.file.originFileObj
      values.VideoFile = values.VideoFile.file.originFileObj
      console.log('values:', values)
      setLoading(true)
      api.addVideo(values).then(res => {
        console.log(res, "res")
        setLoading(false)
        message.success('添加视频成功').then(res => {
          window.history.go(-1)
        })
      }).catch((err) => {
        console.log(err)
        setLoading(false)
      })
    })
  };

  useEffect(() => {
    // getHomeIndicators()
  }, [])

  const propsUPImg: UploadProps = {
    name: 'propsUPImg',
    maxCount: 1,
    beforeUpload: (file) => {
      // const isPNG = file.type === 'image/png';
      // // ["image/jpeg", 'image/jpg', 'image/png']
      // if (!isPNG) {
      //   message.error(`${file.name} is not a png file`);
      // }
      // return isPNG || Upload.LIST_IGNORE;

      let typeArr = ["image/jpeg", 'image/jpg', 'image/png']
      var isPNG = typeArr.indexOf(file.type);
      if (isPNG == -1) {
        console.log(1)
        console.log(file.type)
        message.error(`${file.name} is not a qualified file`);
        return false || Upload.LIST_IGNORE;
      } else {
        console.log(2)
        console.log(file.type)
        return true || Upload.LIST_IGNORE;
      }

      // return new Promise((resolve, reject) => {
      //   let typeArr = ["image/jpeg", 'image/jpg', 'image/png']
      //   var isPNG = typeArr.indexOf(file.type);
      //   if (isPNG == -1) {
      //     message.error(`${file.name} is not a qualified file`);
      //     return reject(false);
      //   }
      //   // const isLt2M = file.size / 1024 / 1024 < 2;
      //   // if (!isLt2M) {
      //   //   message.error('请上传 ≤ 2MB 以内的图片');
      //   //   return reject(false);
      //   // }
      //   return resolve(true);
      // })
    },
    onChange(info) {
      console.log(info, "info")
      if (info.file.status !== 'uploading') {
        console.log(info.file.originFileObj, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
  };

  const propsUPVideo: UploadProps = {
    name: 'propsUPVideo',
    maxCount: 1,
    beforeUpload: (file) => {
      // const isPNG = file.type === 'video/mp4';
      let typeArr = [
        "video/mp4",
        "video/ogg",
        "video/flv",
        "video/avi",
        "video/wmv",
        "video/rmvb",
        "video/mov"]
      var isVideo = typeArr.indexOf(file.type);
      if (isVideo == -1) {
        message.error(`${file.name} is not a qualified file`);
        return false || Upload.LIST_IGNORE;
      } else {
        return true || Upload.LIST_IGNORE;
      }

    },
    onChange(info) {
      console.log(info, "info")
      if (info.file.status !== 'uploading') {
        console.log(info.file.originFileObj, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
  };

  // useEffect(() => {
  //   form.setFieldsValue(indicators)
  // }, [indicators])

  // function getHomeIndicators() {
  //   api.getHomeIndicators().then((res: any) => {
  //     console.log('指标信息', res)
  //     let indicatorsInfo = res || {}
  //     setIndicators(indicatorsInfo)
  //   })
  // }

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  const onCancle = () => {
    window.history.go(-1)
  }

  return (
    <Loading loading={loading} fullscreen={true}>
      <div className={styles.videoEdit}>
        <div className={styles.content}>
          <div>
            <Form
              name="basic"
              form={form}
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 20 }}
              initialValues={{ remember: true }}
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
              autoComplete="off"
              labelAlign="left"
              size="large"
            >
              <Form.Item
                label="Title"
                name="Title"
                rules={[
                  {
                    required: true,
                    message: 'Please input Title!',
                  },
                ]}
              >
                <Input placeholder="Please input Title" />
              </Form.Item>

              <Form.Item
                label="JPTitle"
                name="JPTitle"
                rules={[
                  {
                    required: true,
                    message: 'Please input JPTitle!',
                  },
                ]}
              >
                <Input placeholder="Please input JPTitle" />
              </Form.Item>

              <Form.Item
                label="From"
                name="From"
                rules={[
                  {
                    required: true,
                    message: 'Please input From!',
                  },
                ]}
              >
                <Input placeholder="Please input From" />
              </Form.Item>

              <Form.Item
                label="CoverImgFile"
                name="CoverImgFile"
                rules={[
                  {
                    required: true,
                    message: 'Please upload CoverImg!',
                  },
                ]}
              >
                <Upload {...propsUPImg}>
                  <Button icon={<UploadOutlined />}>Click to Upload</Button>
                </Upload>
              </Form.Item>

              <Form.Item
                label="VideoFile"
                name="VideoFile"
                rules={[
                  {
                    required: true,
                    message: 'Please upload Video!',
                  },
                ]}
              >
                <Upload {...propsUPVideo}>
                  <Button icon={<UploadOutlined />}>Click to Upload</Button>
                </Upload>
              </Form.Item>


              <div className={styles.footer}>
                <Button type="default" className={styles.footerBtn} onClick={onCancle}>
                  Cancel
                </Button>
                <Button type="primary" className={styles.footerBtn} onClick={onFinish}>
                  Submit
                </Button>
              </div>
            </Form>
          </div>
        </div>
      </div>
    </Loading>
  );
}

export default VideoEdit;
View Code

 

标签:info,const,log,..,upload,表单,react,file,console
From: https://www.cnblogs.com/huchong-bk/p/17037475.html

相关文章

  • vue2 element-ui组件二封-表单组件-按钮封装
    这里是一段我们公司过往项目的代码(增删改查项目中的查询/重置按钮)<el-button@click="query()"type="primary"size="mini"><iclass="el-icon-search">查询</i><......
  • fastadmin 表单提交前加验证或者确认弹框效果
    代码:set:function(){Form.api.bindevent($("form[role=form]"),function(){},function(){},function(success,error){layer......
  • 前端高频react面试题整理
    createElement和cloneElement有什么区别?createElement是JSX被转载得到的,在React中用来创建React元素(即虚拟DOM)的内容。cloneElement用于复制元素并传递新的props。区......
  • react的jsx和React.createElement是什么关系?面试常问
    1、JSX在React17之前,我们写React代码的时候都会去引入React,并且自己的代码中没有用到,这是为什么呢?这是因为我们的JSX代码会被Babel编译为React.createElement,我们来......
  • React面试:谈谈虚拟DOM,Diff算法与Key机制
    1.虚拟dom原生的JSDOM操作非常消耗性能,而React把真实原生JSDOM转换成了JavaScript对象。这就是虚拟Dom(VirtualDom)每次数据更新后,重新计算虚拟Dom,并和上一次生成的虚拟......
  • 社招前端react面试题整理
    什么是上下文ContextContext通过组件树提供了一个传递数据的方法,从而避免了在每一个层级手动的传递props属性。用法:在父组件上定义getChildContext方法,返回一个对象,......
  • React Hooks的理解,React Hooks有哪些,解决了什么问题
    一、是什么Hook 是React16.8的新增特性。它可以让你在不编写 class 的情况下使用 state 以及其他的 React 特性至于为什么引入hook,官方给出的动机是解决长......
  • react-vant 所有滚动区下拉都可以触发PullRefresh下拉刷新的问题
    react-vantPullRefresh组件判断是否下拉刷新是从三个维度来判断的:手势的方向手势是否是垂直方向触摸事件的父级滚动区这样就造成了一个问题,不管是内部滚动区或者外部......
  • [强网杯 2019]Upload
    [强网杯2019]Upload考点:1、文件上传 2、php反序列化攻击进到页面里,存在注册功能,所以就不尝试先不尝试sql注入,先注册一个账号登陆进去进去之后有一个上传文件功能,尝试上......
  • react hooks forwardRef, useImperativeHandle使用
    1、React.forwardRefReact.forwardRef 会创建一个React组件,这个组件能够将其接受的 ref 属性转发到其组件树下的另一个组件中。React.forwardRef 接受渲染函数作为参......