实现input框粘贴图片,图片上传

2022-09-27 06:47:23
2024-11-21 20:22:34
vue 复制代码
<template>
  <div>
    <el-input
      v-model="imgSrc"
      type="textarea"
      :placeholder="placeholder"
      @input="setInput"
      @paste.capture.prevent="pasting"
    />
  </div>
</template>
<script setup lang="ts">
  import axios from 'axios';
  import { userStore } from '@/store/module/user';
  import { ElMessage } from 'element-plus';
  const user: any = userStore();
  const imgSrc = ref('');
  const emit = defineEmits(['uploaded']);

  const props = defineProps({
    placeholder: {
      type: String,
      default: '',
    },

    imgSrcData: {
      type: String,
      default: '',
    },
  });

  watch(
    () => props.imgSrcData,
    (newValue, oldValue) => {
      if (newValue !== oldValue) {
        imgSrc.value = newValue;
      }
    },
    {
      immediate: true, //立即执行
    },
  );

  // 监听粘贴事件
  const pasting = (event: { clipboardData: { getData: (arg0: string) => any } }) => {
    console.log(event.clipboardData);
    let txt = event.clipboardData.getData('Text');
    console.log('文本', txt);
    if (typeof txt == 'string') {
      imgSrc.value += txt;
      emit('uploaded', imgSrc.value);
    }
    let file = null;
    const items = (event.clipboardData || window.clipboardData).items;
    console.log(items);
    if (items.length) {
      let canUpload = false;
      for (let i = 0; i < items.length; i++) {
        if (items[i].type.indexOf('image') !== -1) {
          file = items[i].getAsFile();
          handleChange(file);
          if (!canUpload) {
            canUpload = !canUpload;
          }
          break;
        }
      }
    }
  };
  // 上传
  const handleChange = (file: Blob) => {
    let formData = new FormData();
    formData.append('file', file);
    axios
      .post(import.meta.env.VITE_APP_UPLOAD_URL, formData, {
        headers: {
          'Content-type': 'multipart/form-data',
          token: user.getToken(),
        },
      })
      .then((res) => {
        imgSrc.value = res.data.data.info.src;
        emit('uploaded', imgSrc.value);
        ElMessage({ message: '图片上传成功!', type: 'success' });
      })
      .catch((err) => {
        ElMessage({ message: err || '图片上传失败!', type: 'warning' });
      });
  };

  const setInput = () => {
    emit('uploaded', imgSrc.value);
  };
</script>
目录

运营需要亿点资金维持,您的支持,是小白龙创作的动力!!!

昵称
留言
赞赏金额
暂无评论,欢迎留下你的评论