用react写一个图片上传(或文件上传)

<Upload
  {...actionprops}
>
  { systemOne ? systemOne.imgUrl ? <img src={systemOne.imgUrl} alt="图片加载异常" style={
  
  { width: '50%' }} /> : uploadButton: ''}
</Upload>
const actionprops={
  name:"files",
   //onChange:{handleChange},
  showUploadList: false,
  action:'/app/system/unit/4a/uploadHeadImg',
  beforeUpload: beforeUpload,
  onChange: handleChange,
}

文件在上传完成后 file中的状态会改为done 并且会将返回值保存在onchange事件的参数中

这个时候我们就可以利用这个onchange事件来对后续的state做处理,同步更新界面上的图片展示

 
const handleChange = (info:any) => {
   console.log(info.file)
   if (info.file.status === 'done') {
     // Get this url from response in real world.
       if(info.file.response.retCode === '000000'){
         console.log(info.file.response.result)
         systemOne.imgUrl= info.file.response.result

         dispatch({
           type: 'businesSysmanage/updateState',
           payload: {
             systemOne:systemOne
           }
         })
       }

     }


 };
const beforeUpload = (file:any) =>{
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('只支持 JPG/PNG 类型的文件!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片大小不可以超过 2MB!');
  }
  return isJpgOrPng && isLt2M;
}

猜你喜欢

转载自blog.csdn.net/wangzhichaogege/article/details/109719308