Using Upload in react-antd to achieve the function of image cropping-uploading-preview

foreword

Use antd in react to achieve image upload, crop and preview, record the implementation process, I hope it can be helpful to everyone

accomplish

What we use here is the antd framework, to achieve
the function of image uploading, we need to install a plugin antd-img-crop

yarn add antd-img-crop

Then you can use:

import React, {
    
     memo, useState } from 'react'
import {
    
     Upload } from 'antd'
import ImgCrop from ' 
'

export default memo(function Index() {
    
    
  const [fileList, setFileList] = useState([
    {
    
    
      uid: '-1',
      name: 'image.png',
      status: 'done',
      url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    },
  ]);

  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>
      <ImgCrop rotate>
        <Upload
          action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
          listType="picture-card"
          fileList={
    
    fileList}
          onChange={
    
    onChange}
          onPreview={
    
    onPreview}
        >
          {
    
    fileList.length < 5 && '+ Upload'}
        </Upload>
      </ImgCrop>
    </div>
  )
})

Use the <ImgCrop rotate> component, which uses the upload component, and the functions of the related properties used:
action: upload address
listType: built-in style of the upload list, supports three basic styles text, picture and picture-card
fileList: has been uploaded The list of files (controlled)
onChange: This function will be called during uploading, completion, and failure.
onPreview: Callback when the file link or preview icon is clicked

There are more attributes about image upload, you can refer to the official documentation
to see the effect:

insert image description here
antd provides us with a lot of related functions, which is very convenient. You can try it yourself. For more properties, please refer to the official documentation. It is relatively simple to implement such a function. You can also do operations such as uploading files according to your own needs.

Guess you like

Origin blog.csdn.net/weixin_45745641/article/details/123886519
Recommended