How to implement paste upload feature in React?

In React, to implement paste upload functionality, you can use the onPaste event and the FileReader object to handle the paste event and read the pasted file.

Here is a simple implementation example:

  1. In a React component, set up an input element and an img element to display the pasted image.
import React, { useRef } from 'react';

const UploadImage = () => {
  const inputRef = useRef(null);
  const imgRef = useRef(null);

  const handlePaste = (e) => {
    const items = e.clipboardData.items;
    for (let i = 0; i < items.length; i++) {
      const item = items[i];
      if (item.type.indexOf('image') !== -1) {
        const file = item.getAsFile();
        const reader = new FileReader();
        reader.onload = (e) => {
          imgRef.current.src = e.target.result;
        };
        reader.readAsDataURL(file);
      }
    }
  };

  const handleClick = () => {
    inputRef.current.click();
  };

  return (
    <div>
      <input
        type="file"
        accept="image/*"
        ref={inputRef}
        style={{ display: 'none' }}
      />
      <img
        src=""
        alt=""
        ref={imgRef}
        style={{ maxWidth: '100%', maxHeight: '100%' }}
        onPaste={handlePaste}
      />
      <button onClick={handleClick}>选择图片</button>
    </div>
  );
};

export default UploadImage;
  1. In the handlePaste function, first retrieve all items in the clipboard (e.clipboardData.items), then iterate through each item. If the item’s type includes image, convert it to a file object (item.getAsFile()). Next, use a FileReader object to read the file as a DataURL and assign it to the src attribute of the img element to display the pasted image.
  2. In the component, the functionality of choosing an image is implemented using an input element. The input element is hidden (style={{ display: ‘none’ }}) and referenced to inputRef through ref. A button is used to trigger the selection of an image. When the button is clicked, inputRef.current.click() is called to initiate the file selection functionality.

The above code example implements both paste upload feature and image selection feature. You can modify and expand according to your own needs.

bannerAds