react写图片上传

import React, { useState } from 'react';

import { Upload } from 'antd';

//组件总览 - Ant Design (antgroup.com)

//复制组件上传 进行修改为图片上传 上传不得超过五个

import ImgCrop from 'antd-img-crop';

import { Button, message } from 'antd';

const App = () => {

  let [flag,setflag]=useState(true)

  // 图片类型 不符合则上传失败

  const props = {

  beforeUpload: (file) => {

    const isPNG = file.type === 'image/png'||file.type === 'image/jpeg'

    if (!isPNG) {

      message.error(`${file.name} 上传失败`);

    }

    

    return isPNG || Upload.LIST_IGNORE;

  },

  onChange: (info) => {

    console.log(info.fileList);

  },

};

  const [fileList, setFileList] = useState([

    

  ]);

  const onChange = ({ fileList: newFileList }) => {

    setFileList(newFileList);

  };

  const onPreview = async (file) => {

    let src = file.url;

    if (!src) {

      src = await new Promise((resolve) => {

        const reader = new FileReader();

        reader.readAsDataURL(file.originFileObj);

        reader.onload = () => resolve(reader.result);

      });

    }

    const image = new Image();

    image.src = src;

    const imgWindow = window.open(src);

    imgWindow?.document.write(image.outerHTML);

  };

  return (

    <div>

      {/* 点击上传出图片文件 */}

      <button onClick={()=>setflag(!flag)}>上传</button>

      {/* 连接后台OSS服务器 */}

      {

        !flag?<ImgCrop rotationSlider>

      <Upload

        {...props}

        action="http://localhost:3000/upload"

        listType="picture-card"

        fileList={fileList}

        onChange={onChange}

        onPreview={onPreview}

      

      >

        {fileList.length < 5 && '+ Upload'}

      </Upload>

    </ImgCrop>:""

      }

    </div>

  );

};

export default App;

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值