问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

使用Element UI实现Ctrl + V图片上传功能

创作时间:
作者:
@小白创作中心

使用Element UI实现Ctrl + V图片上传功能

引用
51CTO
1.
https://blog.51cto.com/miaow/12515706

本文将介绍如何在Element UI的拖拽上传组件中实现Ctrl + V图片上传功能。通过监听键盘事件,我们可以捕获粘贴板中的图片数据,并将其转换为File对象进行上传。文章将分两个版本逐步实现这一功能:第一个版本实现获取粘贴板中的图片文件,第二个版本则进一步实现在上传过程中展示压缩图片的功能。

版本V1:实现获取粘贴板中的文件

注意,本案例需要在你已经安装了Element UI并在项目中正确配置的情况下进行。第一个版本仅适合上传jpeg和png的图片。

创建拖拽上传组件

假设你已经有一个基本的拖拽上传组件,我们可以在此基础上添加Ctrl + V功能。

监听粘贴事件

我们需要在页面中监听paste事件,当用户按下Ctrl + V时,捕获粘贴板中的图片数据。

处理粘贴事件

在捕获到图片数据后,将其转换为File对象,并调用上传方法。

代码如下:

<template>
  <div>
    <el-upload
      drag
      action="https://jsonplaceholder.typicode.com/posts/"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      multiple
      ref="upload"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">只能上传jpg/png文件,且不超过500kb</div>
    </el-upload>
  </div>
</template>
<script>
import { Upload } from 'element-ui';
export default {
  name: 'DragUpload',
  methods: {
    handlePaste(event) {
      // 捕获粘贴事件
      const items = event.clipboardData.items;
      for (let i = 0; i < items.length; i++) {
        if (items[i].type.indexOf('image') !== -1) {
          // 获取图片文件
          const file = items[i].getAsFile();
          this.handleFile(file);
          break;
        }
      }
    },
    handleFile(file) {
      // 将文件添加到上传队列
      this.$refs.upload.handleStart(file);
      this.$refs.upload.submit();
    },
    handlePreview(file) {
      console.log('Preview:', file);
    },
    handleRemove(file, fileList) {
      console.log('Remove:', file, fileList);
    },
    beforeUpload(file) {
      const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt500K = file.size / 1024 < 500;
      if (!isJPGorPNG) {
        this.$message.error('只能上传 JPG/PNG 格式的图片!');
      }
      if (!isLt500K) {
        this.$message.error('图片大小不能超过 500KB!');
      }
      return isJPGorPNG && isLt500K;
    }
  },
  mounted() {
    // 监听粘贴事件
    document.addEventListener('paste', this.handlePaste);
  },
  beforeDestroy() {
    // 移除粘贴事件监听
    document.removeEventListener('paste', this.handlePaste);
  }
};
</script>
  1. HTML部分:使用el-upload组件创建一个拖拽上传区域。
  2. JavaScript部分:
  • handlePaste方法:捕获粘贴事件,检查粘贴板中的数据是否为图片文件,如果是,则调用handleFile方法。
  • handleFile方法:将图片文件添加到上传队列,并提交上传。
  • mounted生命周期钩子:添加粘贴事件监听器。
  • beforeDestroy生命周期钩子:移除粘贴事件监听器,防止内存泄漏。

随便截图一张,我们这个时候ctrl + v就可以发现他可以获取我们粘贴板中的文件。

我们到这一步发现,图片网页是获取到。这个时候你在跟着你的业务,传递相关参数,这第V1版本就可以用了。

第二版本V2:可以直接在粘贴的过程在下面以压缩图片的形式展示图片

<template>
  <div>
    <el-upload
      drag
      :action="uploadFileUrl"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      multiple
      ref="upload"
      :file-list="fileList"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">只能上传jpg/png文件,且不超过500kb</div>
    </el-upload>
    <!-- 显示上传后的文件 -->
    <div v-for="(file, index) in fileList" :key="index" class="uploaded-file">
      <div v-if="isImage(file.name)">
        <img :src="file.url" alt="Uploaded Image" class="uploaded-image" />
        <el-button type="text" @click="removeFile(index)">移除</el-button>
      </div>
      <div v-else>
        <span>{{ file.name }}</span>
        <el-button type="text" @click="removeFile(index)">移除</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import { Upload } from 'element-ui';
export default {
  name: 'DragUpload',
  data() {
    return {
      fileList: []
    };
  },
  methods: {
    handlePaste(event) {
      const items = event.clipboardData.items;
      for (let i = 0; i < items.length; i++) {
        if (items[i].type.indexOf('image') !== -1) {
          const file = items[i].getAsFile();
          this.handleFile(file);
          break;
        }
      }
    },
    handleFile(file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        this.fileList.push({
          name: file.name,
          url: e.target.result
        });
      };
      reader.readAsDataURL(file);
      this.$refs.upload.handleStart(file);
      this.$refs.upload.submit();
    },
    handlePreview(file) {
      console.log('Preview:', file);
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    beforeUpload(file) {
      const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt500K = file.size / 1024 < 500;
      if (!isJPGorPNG) {
        this.$message.error('只能上传 JPG/PNG 格式的图片!');
      }
      if (!isLt500K) {
        this.$message.error('图片大小不能超过 500KB!');
      }
      return isJPGorPNG && isLt500K;
    },
    handleSuccess(response, file, fileList) {
      // 更新 fileList
      this.fileList = fileList.map(f => ({
        name: f.name,
        url: f.url || f.response.url // 假设服务器返回的响应中有 url 字段
      }));
    },
    removeFile(index) {
      this.fileList.splice(index, 1);
    },
    isImage(fileName) {
      return fileName.toLowerCase().endsWith('.jpg') || fileName.toLowerCase().endsWith('.png');
    }
  },
  mounted() {
    document.addEventListener('paste', this.handlePaste);
  },
  beforeDestroy() {
    document.removeEventListener('paste', this.handlePaste);
  }
};
</script>
<style scoped>
.uploaded-file {
  margin-top: 10px;
  display: flex;
  align-items: center;
}
.uploaded-image {
  max-width: 100px;
  max-height: 100px;
  margin-right: 10px;
}
</style>

如图所示。Ctrl + V就实现到了这一步。这里有问题,那就是你看一下,点击上传后的图片是否会显示出来呢?

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号