欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

antd 里面的Upload图片上传

程序员文章站 2022-06-03 11:20:16
...

Antd 里面的Upload

antd 里面的Upload图片上传

import React,{useState} from 'react';
import { Upload, Icon, message,Spin } from 'antd';
import  serviceApi from '@/utils/api';
import {MessageTip} from '@/utils/tools.js'
import './upload.css'
// 上传单张图片
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
function beforeUpload(file) {
    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;
}
 
const UploadAvatar = (props) =>{

    const [loading,setLoading] = useState(false)
    const [imageUrl,setImageUrl] = useState('')
    const handleChange = info => {
      if (info.file.status === 'uploading') {
        setLoading(true)
        return;
      }
      if (info.file.status === 'done') {
        getBase64(info.file.originFileObj, imageUrl =>{
          setLoading(false)
          if(info.file.response.success){
            const {module} = info.file.response   // 返回的图片地址
            props.childImg(module)   // 传给父级的
            setImageUrl(imageUrl)
            MessageTip('success','文件上传成功')
          }
        });
      }
    };
    const uploadButton = (
      <div>
        {
          loading?<Spin />:''
        }
        <div className="ant-upload-text">Upload</div>
      </div>
    );
      return (
        <Upload
          name="file"
          listType="picture-card"
          className="avatar-uploader"
          showUploadList={false}
          action={serviceApi.uploadFile}
          data={{type:1}}   // type 1图片  2试卷
          beforeUpload={beforeUpload}
          onChange={handleChange}
        >
          {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
        </Upload>
      );
}
export default UploadAvatar;