Ctrl + V 粘贴上传文件,以React + Antd为示例

在这里插入图片描述


完整代码

import React, {
    
     useState } from 'react'
import {
    
     Upload } from 'antd'
import plusIcon from './plus.png'
import {
    
     axios } from '@/common'
export default () => {
    
    
  const [fileList, setFileList] = useState([])

  // 解析粘贴板
  const pasteUpload = (event) => {
    
    
    event.stopPropagation()
    console.log(event)
    const data = event.clipboardData || window.clipboardData
    const items = data.items
    let tempFile = null // 存储文件数据
    if (items && items.length) {
    
    
      // 检索剪切板items
      for (const item of items) {
    
    
        if (item.type.indexOf('image') !== -1) {
    
    
          tempFile = item.getAsFile()
          break
        }
      }
    }
    console.log('tempFile', tempFile)
    handleUpload(tempFile)
  }

  // 手动上传粘贴文件
  const handleUpload = (file) => {
    
    
    if (!file) {
    
    
      return
    }
    // 可以在这里处理文件类型与文件size
    // TODO 
    
    
    const formData = new FormData()
    formData.append('file', file)
    axios.post('/files/upload', formData).then(({
     
      flag, data }) => {
    
    
      if (flag === 1) {
    
    
        // 回显图片
        const newFile = {
    
    
          ...file,
          originFileObj: file,
          status: 'done',
          fileId: data
        }
        setFileList([...fileList, newFile])
      }
    })
  }

  const handleChange = ({
     
      fileList: newFileList }) => setFileList(newFileList)

  const props = {
    
    
    action: '/files/upload',
    onChange: handleChange,
    multiple: true,
    listType: 'picture-card'
  }

  return (
    <>
      <div className="upload-paste" onPaste={
    
    pasteUpload}>
        <Upload {
    
    ...props} fileList={
    
    fileList}>
          <img style={
    
    {
    
     height: 28 }} src={
    
    plusIcon} alt="选择图片" />
        </Upload>
      </div>
      <style jsx>{
    
    `
      	.upload-paste {
          border: 1px dashed #d9d9d9;
          border-radius: 2px;
          cursor: copy;
          transition: border-color .3s;
          .ant-upload-list-picture-card-container {
             cursor: auto;
          }
        }
      `}</style>
    </>
  )
}

猜你喜欢

转载自blog.csdn.net/qq_41887214/article/details/126275009