Element UI上传图片和PDF,支持预览,并支持复制黏贴上传

背景

如上图,使用Element UI的el-upload组件,并且预览的时候可以展示图片和PDF格式文件;

做法

index.vue

javascript 复制代码
<template>
  <div>
    <el-upload
      v-model="diaForm.list"
      :limit="5"
      :on-exceed="handleExceed"
      :on-preview="handlePreview"
      :before-upload="beforeAvatarUpload"
      :on-remove="handleRemove"
      :headers="reqHeaders"
      :on-success="onUploadSuccess"
      :action="uploadUrl()"
      :file-list="resultFileList"
      list-type="picture"
      class="upload-files"
      accept=".png,.jpeg,.gif,.pdf,.jpg,.JPG">
      <div class="upfile-btn">
        <d2-icon name="document-upload" class="document-upload" />
        <div>点击上传+拖拽上传</div>
      </div>
    </el-upload>
  </div>
</template>

<script>
import { workOrderUploadUlr } from '@/api/upload';
export default {
  data() {
    return {
      diaForm: {
        desc: '',
        list: [],
      },
      resultFileList: [],
    };
  },
  methods: {
    // 限制上传个数不超过5个
    handleExceed(files, fileList) {
      if (fileList && fileList.length == 5) {
        this.$message.warning('XXXX');
      }
    },
    handlePreview(file) {
      console.log(file);
    },
    // 限制不超过30M
    beforeAvatarUpload(file) {
      const isLt5M = file.size / 1024 / 1024 < 30;
      if (!isLt5M) {
        this.$message.error('XXXX');
      }
      return isLt5M;
    },
    // 移除文件
    handleRemove(file, fileList) {
      if (!file) {
        return;
      }
      const index = this.resultFileList.findIndex(item => item.uid === file.uid);
      this.resultFileList.splice(index, 1);
    },
    // 设置请求头里面的token 和 userId
    reqHeaders() {
      return {
        token: this.$util.cookies.token,
        userId: this.info ? this.info.userId : '',
      };
    },
    // 上传成功,返回
    onUploadSuccess(response, file, fileList) {
      if (response && response.code === 'APPLY_SUCCESS') {
        if (response.data) {
          this.resultFileList.push({
            url: response.data.url,
            name: response.data.name,
            uid: file.uid
          });
          this.dealPDF();
          setTimeout(() => {
            this.dealPDF();
          }, 1);
        }
      } else if (response && response.msg) { console.log('upload failed', response.msg); }
    },
    // 上传的服务器的地址
    uploadUrl() {
      return workOrderUploadUlr();
    },
    dealPDF() {
      var liElements = document.querySelectorAll('ul.el-upload-list.el-upload-list--picture li.el-upload-list__item');
      liElements.forEach(function(liElement) {
        var aElement = liElement.querySelector('a.el-upload-list__item-name');
        if (aElement && aElement.textContent.includes('.pdf')) {
          var imgElement = liElement.querySelector('img.el-upload-list__item-thumbnail');
          if (imgElement) {
            imgElement.src = 'https://sg-pay69e4d75928dac6fddd3229a/file.png'; // 替换为你想要的新图片的URL
          }
        }
      });
    },
  }
};
</script>

<style>

</style>

upload.js

javascript 复制代码
// import request from '@/plugin/axios';
const host = require('../../host');
// 工单文件上传
export function workOrderUploadUlr(hostType = 'BASIC_GATE') {
  return host.getBaseUrl(hostType) + 'xxxxx/file/upload';
}

再次基础上,我们对上面代码进行改造,添加监听past事件

javascript 复制代码
<template>
  <div>
    <el-upload
      v-model="diaForm.list"
      :limit="5"
      :on-exceed="handleExceed"
      :on-preview="handlePreview"
      :before-upload="beforeAvatarUpload"
      :on-remove="handleRemove"
      :headers="reqHeaders"
      :on-success="onUploadSuccess"
      :action="uploadUrl()"
      :file-list="resultFileList"
      list-type="picture"
      class="upload-files"
      accept=".png,.jpeg,.gif,.pdf,.jpg,.JPG">
      <div class="upfile-btn">
        <d2-icon name="document-upload" class="document-upload" />
        <div>点击上传+拖拽上传 + 复制黏贴 + 截图上传</div>
      </div>
    </el-upload>
  </div>
</template>

<script>
import { workOrderUploadUlr } from '@/api/upload';
import { evaluateUpload } from '@/api/auth';
export default {
  data() {
    return {
      diaForm: {
        desc: '',
        list: [],
      },
      resultFileList: [],
    };
  },
  mounted() {
    document.addEventListener('paste', this.handlePaste);
  },
  beforeDestroy() {
    document.removeEventListener('paste', this.handlePaste);
  },
  methods: {
    async handlePaste(event) {
      const clipboardData = event.clipboardData || window.clipboardData;
      if (clipboardData) {
        const items = clipboardData.items;
        if (items && items.length > 0) {
          for (let i = 0; i < items.length; i++) {
            const item = items[i];
            if (item.kind === 'file' && item.type.startsWith('image/')) {
              const file = item.getAsFile();
              const formData = new FormData();
              formData.append('file', file);
              if (file) {
                evaluateUpload(formData, {
                  token: this.$util.cookies.token,
                  userId: this.info ? this.info.userId : '',
                })
                  .then((response) => {
                    const { data, code } = response.data || {};
                    // 上传成功,应该返回
                    if (code === 'APPLY_SUCCESS') {
                      if (data) {
                        this.resultFileList.push({
                          url: data.url,
                          name: data.name,
                          uid: file.uid
                        });
                      }
                      console.log(this.resultFileList, '剪贴成功数据');
                    } else if (response && response.msg) { console.log('upload failed', response.msg); }
                  }).catch((error) => {
                    console.log(error);
                  });
              }
            }
          }
        }
      }
    },
    // 限制上传个数不超过5个
    handleExceed(files, fileList) {
      if (fileList && fileList.length == 5) {
        this.$message.warning('XXXX');
      }
    },
    handlePreview(file) {
      console.log(file);
    },
    // 限制不超过30M
    beforeAvatarUpload(file) {
      const isLt5M = file.size / 1024 / 1024 < 30;
      if (!isLt5M) {
        this.$message.error('XXXX');
      }
      return isLt5M;
    },
    // 移除文件
    handleRemove(file, fileList) {
      if (!file) {
        return;
      }
      const index = this.resultFileList.findIndex(item => item.uid === file.uid);
      this.resultFileList.splice(index, 1);
    },
    // 设置请求头里面的token 和 userId
    reqHeaders() {
      return {
        token: this.$util.cookies.token,
        userId: this.info ? this.info.userId : '',
      };
    },
    // 上传成功,返回
    onUploadSuccess(response, file, fileList) {
      if (response && response.code === 'APPLY_SUCCESS') {
        if (response.data) {
          this.resultFileList.push({
            url: response.data.url,
            name: response.data.name,
            uid: file.uid
          });
          this.dealPDF();
          setTimeout(() => {
            this.dealPDF();
          }, 1);
        }
      } else if (response && response.msg) { console.log('upload failed', response.msg); }
    },
    // 上传的服务器的地址
    uploadUrl() {
      return workOrderUploadUlr();
    },
    dealPDF() {
      var liElements = document.querySelectorAll('ul.el-upload-list.el-upload-list--picture li.el-upload-list__item');
      liElements.forEach(function(liElement) {
        var aElement = liElement.querySelector('a.el-upload-list__item-name');
        if (aElement && aElement.textContent.includes('.pdf')) {
          var imgElement = liElement.querySelector('img.el-upload-list__item-thumbnail');
          if (imgElement) {
            imgElement.src = 'https://sg-pay69e4d75928dac6fddd3229a/file.png'; // 替换为你想要的新图片的URL
          }
        }
      });
    },
  }
};
</script>

<style>

</style>

auth.js

javascript 复制代码
import request from '@/plugin/axios';
import {
  post,
} from '@/plugin/axios/helper.js';
import md5 from 'md5';

// 登录新
export function evaluateUpload(data = {}, token) {
  return request({
    url: '/file/workOrder/upload',
    method: 'post',
    useError: true,
    data: data,
    headers: { 'Content-Type': 'multipart/form-data', ...token },
    hostType: 'BASIC_GATE',
  });
}

这里主要需要再header中设置 'Content-Type': 'multipart/form-data' 还有依赖的Token等字段内容。

效果展示

随便屏幕截图

然后 黏贴

发现图片已经上传到组件中了