react 图片上传问题

react 图片上传实例

1.通过上传组件实现图片上传

实现效果:

 技术:

TS+React,Ant Design的Avatar 头像组件,Upload组件

栅格布局,左侧是头像图片,右侧是上传按钮和提示语

           <Row>
            <Col span={6}>
           //头像部分,没有照片显示默认图标
              {imageUrl ? (
                <Avatar src={imageUrl} style={{  150, height: 150 }} />
              ) : (
                <Avatar size={150} icon={loading ? <LoadingOutlined /> : <UserOutlined />} />
              )}
            </Col>
            <Divider type="vertical" style={{ height: 150 }} />
            <Col span={10} >
         //上传组件 不显示文件列表
              <Upload
                name="file"
                showUploadList={false}
                beforeUpload={beforeUpload}
                onChange={handleChange}
              >
                <Button>
                 Upload New Avatar
                </Button>
                <div>
                The maximun file size allowed is 200KB
                <div/>
              </Upload>
            </Col>
          </Row>
handleChange()函数接收的参数info是一个对象,有两个参数,file和fileList。取file.target文件,通过reader.readAsDataURL()方法,将文件类型转换成base64类型,设置为imageUrl。
上面Avatar组件scr引用对应的imageUrl,就可以显示头像了

// 上传前图片的校验,图片小于60KB
  const beforeUpload=(file:any)=>{
    const isLimit = file.size / 1024 < 200;
    if (!isLimit) {
      message.error('Image must smaller than 200KB!');
    }
    return isLimit;
  }
//图片上传完,转换成base64类型,实现预览
const getBase64 = (img: any) => {
    const reader = new FileReader();
    reader.readAsDataURL(img);
    reader.onloadend = () => {
      const url = reader.result;
      setImageUrl(url);
    };
  };
//处理图片,判断图片状态
  const handleChange = (info: any) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      setLoading(false);
      getBase64(info.file.originFileObj);
    }
  };

2.通过原生方法,input标签的type设为file类型,accept表示文件上传类型,accept=’image/*'表示图片类型文件,在onchange函数对图片进行处理

 <input
      className='select-img-input'
      onChange={(e) => onImgFileFn(e)}
      type='file'
      name='fileSelect'
      accept='image/*'
  />

对图片文件处理,实现预览与上同理

//选中图片,预览头像
  const onImgFileFn = (e) => {
    e.preventDefault()
//获取图片文件,图片类型,图片大小
    const file = e.target.files[0]
    const type = file.type
    const size = file.size
    const regularType = ['image/png', 'image/jpg', 'image/jpeg']
//图片类型限制
    if (regularType.indexOf(type.toLowerCase()) === -1) {
      Toast.fail('Only supports PNG images!')
      return false
    }
//图片大小限制
    if (size && size > 5242880) {
      // 5 * 1024 * 1024,size的单位是字节
      Toast.fail('The image size should less than 5M!')
      return false
    }
//图片文件转成base64格式
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onloadend = () => {
      setImgPreviewUrl(reader.result)
    }
  }

如果有需要,base64格式可以转换成二进制格式

  //Base64转换成二进制
  const dataURItoBlob=(dataURI)=> {
    const byteString = atob(dataURI.split(',')[1])
    const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
    const ab = new ArrayBuffer(byteString.length)
    const ia = new Uint8Array(ab)
    for (let i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i)
    }
    return new Blob([ab], { type: mimeString })
  }
    const blob = dataURItoBlob(imgPreviewUrl)
    const blobFile = new File([blob], 'avatar', { type: blob.type })
原文地址:https://www.cnblogs.com/hl-tyc/p/14592931.html