vue+antd——实现拖拽上传文件——技能提升

最近看到有2023年博客之星的入围状况,提示我还差24篇高质量文章才可以入围。前两年由于比较勤奋,文章篇数足够,因此没有遇到这种提示过。现在补上几篇文章,希望可以入围吧。

在这里插入图片描述

1.html代码

<template>
  <div class="clearfix">
    <a-upload-dragger
      :action="`${baseURL}/api/file-management/file/upload`"
      :fileList="fileList"
      :headers="headers"
      @preview="handlePreview"
      @change="handleChange"
      :multiple="false"
    >
      <p class="ant-upload-drag-icon">
        <a-icon type="inbox" />
      </p>
      <p class="ant-upload-text">
        点击或拖拽实现上传
      </p>
      <p class="ant-upload-hint">
        支持单次或批量上传。严格禁止上传公司数据或其他被禁止的文件。
      </p>
    </a-upload-dragger>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

2.script部分代码

<script>
const uuid = require('uuid');
import Cookie from 'js-cookie';
export default {
    
    
  props: {
    
    
    value: {
    
    
      type: String,
      value: '',
    },
    maxCount: {
    
    
      type: Number,
      default: 1,
    },
  },
  mounted() {
    
    
    this.refresh();
  },
  data() {
    
    
    return {
    
    
      previewVisible: false,
      previewImage: '',
      fileList: [],
      internelValue: {
    
    },
      baseURL: process.env.VUE_APP_API_BASE_URL,
      headers: {
    
     Authorization: Cookie.get('Authorization') },
    };
  },
  watch: {
    
    
    value(val) {
    
    
      this.value = val;
      this.refresh();
    },
  },
  methods: {
    
    
    multiple() {
    
    
      return this.maxCount > 1;
    },
    refresh() {
    
    
      if (this.maxCount < 1) {
    
    
        throw 'maxCount必须>=1';
      }
      if (this.value) {
    
    
        let urls = [];
        urls.push(this.value);
        this.fileList = urls.map((x) => {
    
    
          return {
    
    
            name: x,
            uid: uuid.v4(),
            status: 'done',
            id: x,
            url: `${
      
      this.baseURL}/api/file-management/file/${
      
      x}/getFile`,
          };
        });
      } else {
    
    
        this.fileList = [];
      }
    },
    handleCancel() {
    
    
      this.previewVisible = false;
    },
    handlePreview(file) {
    
    
      this.previewImage = file.url || file.thumbUrl;
      this.previewVisible = true;
    },
    handleChange({
     
      file, fileList }) {
    
    
      this.fileList = fileList;
      if (file.status == 'done' || file.status == 'removed') {
    
    
        var values = this.fileList
          .filter((x) => x.status == 'done')
          .map((x) => x.id || x.response.fileInfo.id);
        var newValue = this.maxCount == 1 ? values[0] : values;
        this.internelValue = newValue;
        this.$emit('input', newValue);
      }
    },
  },
};
</script>

猜你喜欢

转载自blog.csdn.net/yehaocheng520/article/details/131515445