antd Form.item upload 上传检验格式大小

3 篇文章 0 订阅
/*
@name: MapImportDraw
@author: diaojw
@time: 2022-10-22 18:31:38
@description:
*/
import React, {useEffect, useState} from 'react';
import { PlusOutlined } from '@ant-design/icons';
import {Button, DatePicker, Form, Input, message, Modal, Select, Upload} from 'antd';
import {RcFile} from "antd/es/upload";
import {Props, StoreEnum} from "@pages/deviceBindWeb/typing";
import {DrawerForm} from "@ant-design/pro-form";
import {reqCompanySelectList, reqStationMapAdd, reqStationMapUpdate} from "@pages/deviceBindWeb/api";
import OrgSelectList from "@hooks/orgSelectList";
import {reqCopyMapPositionInfo, reqMapInfoAdd, reqMapInfoUpdate} from "@pages/deviceBindWeb/api2";
import useAllMapInfo from "@hooks/useAllMapInfo";

enum Title {
 add = '新增',
 edit = '编辑',
 copy = '复制',
}
interface Interface {
 factoryInfoArr:any;
 parkInfoArr:any;
}

const MapImportDraw: React.FC<Props & Interface> = (props) => {
 const {state, dispatch,factoryInfoArr,parkInfoArr } = props
 const [form] = Form.useForm<{ name: string; company: string }>();
 const [openDraw, setOpenDraw] = useState(false)
 const [loading, setLoading] = useState(false)
 const [previewOpen, setPreviewOpen] = useState(false);
 const [previewImage, setPreviewImage] = useState('');
 const [titleName, setTitleName] = useState('')
 const [initialValuesForm, setInitialValuesForm] = useState<any>({})
 const [infofile, setFileList] = useState<any>();
 const [comanyCodeListArr, setComanyCodeListArr] = useState<any>([]);

 const curOrgcode = Form.useWatch('orgCode', form);

 useEffect( ()=>{
  if(curOrgcode){
   getCompanyListArr(curOrgcode)
  }
 },[curOrgcode])

 const orgListArr = OrgSelectList('businessOrgInfo')
 const mapListArr = useAllMapInfo()

 // 获取子公司
 const getCompanyListArr = async (val:any)=>{
  const res = await reqCompanySelectList(val);
  if (!res) return;
  let companyList = res.data.data;
  setComanyCodeListArr(companyList)
 }

 const handleCancel = () => setPreviewOpen(false);

 const handleChange: any = (info: any) => {
  console.log('info.file', info.file)
  setFileList(info.file)
  if (info.file.status === 'uploading') {
   setLoading(true);
   console.log('uploading')
   // setFileList({status:'error', uid:'-5',name:'error'})
   return;
  }
  if (info.file.status === 'done') {
   setFileList(info.file)
   // Get this url from response in real world.
  }
  if (info.file.status === 'error') {
   setLoading(false);
   message.error('上传失败');
  }
 };
 // 上传前
 const beforeUpload:any = (file: any) => {
  const isJpgOrPng = file.type === 'image/png' ;
  if (!isJpgOrPng) {
   message.error('仅支持png格式');
   return
  }
  const isLt2M = file.size / 1024 / 1024 < 10;
  if (!isLt2M) {
   message.error('最大不超过10MB!');
   setFileList({status:'error', uid:'-5'})
   return
  }
  return false
  /*return new Promise((resolve,reject)=>{
   const isJpgOrPng = file.type === 'image/png' ;
   if (!isJpgOrPng) {
    message.error('仅支持png格式');
    return reject(false)
   }
   const isLt2M = file.size / 1024 / 1024 < 10;
   if (!isLt2M) {
    message.error('最大不超过10MB!');
    return reject(false)
   }
   return resolve(true)
  })*/

 };
 const getBase64 = (file: RcFile): Promise<string> =>
  new Promise((resolve, reject) => {
   const reader = new FileReader();
   reader.readAsDataURL(file);
   reader.onload = () => resolve(reader.result as string);
   reader.onerror = error => reject(error);
  });
 // 预览
 const handlePreview = async (file: any) => {
  // let file = fileArr[0]
  console.log('file', file)
  if (!file.url && !file.preview) {
   file.preview = await getBase64(file.originFileObj as RcFile);
  }
  setPreviewImage(file.url || (file.preview as string));
  setPreviewOpen(true);
 };

  // 新增
 useEffect(()=>{
  if(state[StoreEnum.deviceInfoAdd]){
   setTitleName(Title.add)
   setOpenDraw(true)
   setInitialValuesForm({})
  }

 },[state[StoreEnum.deviceInfoAdd]])
 // 编辑
 useEffect(()=>{
   let data = state[StoreEnum.deviceInfoEdit]
  if(data){
   if(data.type === 'edit'){
    setTitleName(Title.edit)
   } else {
    setTitleName(Title.copy)
   }

   let file = [{
    url: data.data.mapUrl,
    uid: data.data.id,
    status: 'done',
    type: 'image/png'
   }]
   setOpenDraw(true)
   console.log('data', {...data.data, file})
   setInitialValuesForm({...data.data, file})
  }

 },[state[StoreEnum.deviceInfoEdit]])

 // 关闭弹窗
 const onCloseHandler = ()=>{
  setOpenDraw(false)
  setInitialValuesForm({})
 }
 // 上传按钮
 const uploadButton = (
  <div>
   {/*{loading ? <LoadingOutlined /> : <PlusOutlined />}*/}
   <PlusOutlined />
   <div style={{ marginTop: 8 }}>上传CAD</div>
   <span style={{fontSize:'12px', color:'#ccc'}}>只支持.png格式,小于10M</span>
  </div>
 );

 // add edit res
 const resHandler = (res:any)=>{
  if(res.data.code === 200){
   message.success('提交成功');
   dispatch({
    type: StoreEnum.refreshDeviceInfo,
    value:{}
   })
   setInitialValuesForm({})
   setOpenDraw(false)
   return
  } else {
   message.error(res.data.msg)
   return
  }
 }
 return (
  <>
   <DrawerForm<{
    name: string;
    company: string;
   }>
    width={600}
    title={titleName}
    form={form}
    visible={openDraw}
    autoFocusFirstInput
    drawerProps={{
     destroyOnClose: true,
     onClose: onCloseHandler,
    }}
    labelCol={{ span: 6 }}
    wrapperCol={{ span: 16 }}
    layout={`horizontal`}
    submitTimeout={2000}
    initialValues={initialValuesForm}
    onFinish={async (values:any) => {
     let orgObj:any = orgListArr.find((item:any)=>item.dicKey === values.orgCode)
     let companyObj:any = comanyCodeListArr.find((item:any)=>item.companyCode === values.companyCode)
     let factObj:any = factoryInfoArr.find((item:any)=>item.dicKey === values.factoryCode)
     let objValues = {
      ...values,
      orgName: orgObj?.dicValue,
      companyName: companyObj?.companyName,
      factoryName: factObj?.dicValue
     }
     let formData = new FormData()
     for (var val in objValues) {
      if(val!= 'file'){
       formData.append(val, objValues[val])
      }
     }
     console.log('values, values', objValues)
     if(titleName === '复制'){
      // 复制位置绑定
      const res:any = await reqCopyMapPositionInfo(objValues)
      resHandler(res)
      return
     }
     const isJpgOrPng =  objValues?.file && (objValues?.file[0].type === 'image/png') || objValues?.file[0].type === 'image/svg+xml';
     const isLt2M = objValues?.file && objValues?.file[0].size ?  objValues?.file[0].size / 1024 / 1024 < 10 : true;
     if(isJpgOrPng && isLt2M){
      if(titleName === '新增'){
       if(!infofile){
        message.error('请上传CAD图片')
        return
       }
       formData.append('file',infofile)
       const res:any = await reqMapInfoAdd(formData)
       resHandler(res)
      } else if(titleName === '编辑'){
       if(values.file[0].url){
        formData.append('file', '')
       } else {
        formData.append('file',infofile)
       }
       formData.append('id',initialValuesForm.id)
       formData.append('mapNo',initialValuesForm.mapNo)
       const res:any = await reqMapInfoUpdate(formData)
       resHandler(res)
      }
     } else {
      message.error('请确认上传图片格式,!');
     }
    }}
   >
    {
     (titleName === '编辑' || titleName === '新增') &&
     <Form.Item label="名称" name={`mapName`} rules={[{ required: true }]}>
      <Input/>
     </Form.Item>
    }
    <Form.Item label="事业部" name={`orgCode`} rules={[{ required: true }]}>
     <Select placeholder={`请选择`}>
      {
       orgListArr.map((item:any)=>{
        return (<Select.Option
         value={item.dicKey}
         key={item.dicKey}>{item.dicValue}</Select.Option>)
       })
      }
     </Select>
    </Form.Item>
    <Form.Item label="子公司" name={`companyCode`} rules={[{ required: true }]}>
     <Select placeholder={`请选择`}>
      {
       comanyCodeListArr.map((item:any)=>{
        return (<Select.Option
         value={item.companyCode}
         key={item.companyCode}>{item.companyName}</Select.Option>)
       })
      }
     </Select>
    </Form.Item>
    <Form.Item label="工厂" name={`factoryCode`} rules={[{ required: true }]}>
     <Select placeholder={`请选择`}>
      {
       factoryInfoArr.map((item:any)=>{
        return (<Select.Option
         value={item.dicKey}
         key={item.dicKey}>{item.dicValue}</Select.Option>)
       })
      }
     </Select>
    </Form.Item>
    {
     (titleName != '编辑' && titleName != '新增') &&
     <Form.Item label="地图" name={`name`} rules={[{ required: true }]}>
      <Select placeholder={`复制来源地图所属子公司 名称 版本号`}>
       {
        mapListArr.map((item:any)=>{
         return (<Select.Option
          value={item.mapNo}
          key={item.mapNo}>{item.mapName}</Select.Option>)
        })
       }
      </Select>
     </Form.Item>
    }
    {
     (titleName === '编辑' || titleName === '新增') &&
      <>
       <Form.Item label="版本号" name={`version`} rules={[{ required: true }]}>
        <Input placeholder={`请输入`}/>
       </Form.Item>
       <Form.Item label="CAD地图" name={`file`}
             valuePropName="fileList"
             getValueFromEvent={e => {
              if(e.file?.status){ // 图片格式校验不显示图片
               return []
              } else {
               if (Array.isArray(e)) {
                return e;
               }
               return e && e.fileList;
              }

             }}>
        <Upload
         name="avatar"
         listType="picture-card"
         className="avatar-uploader"
         maxCount={1}
         fileList={[infofile]}
         style={{width:'400px'}}
         accept={`.png`}
         beforeUpload={beforeUpload}
         onChange={handleChange}
         onPreview={handlePreview}
         customRequest= {async (options) => {
          const formData = new FormData()
          formData.append('file', options.file)
         }}

        >
         {/*{imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}*/}
         {uploadButton}
        </Upload>
       </Form.Item>
       <Form.Item label=" " noStyle >
        <div style={{marginLeft:'120px'}}>更新地图后请更新版本号</div>
       </Form.Item>
      </>
    }




   </DrawerForm>
   <Modal open={previewOpen} title={`图片预览`} footer={null} onCancel={handleCancel}>
    <img alt="example" style={{ width: '100%' }} src={previewImage} />
   </Modal>
  </>

 );
}

export default MapImportDraw;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值