Newer
Older
KaiFengPC / src / components / ImageFileUpload / index.vue
@zhangdeliang zhangdeliang on 12 Jun 6 KB update
<template>
  <!-- 公共图片文件上传 -->
  <div class="publicImgFileUpload">
    <el-upload
      v-model:file-list="fileList"
      action="#"
      :auto-upload="false"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :limit="limit"
      :list-type="listType"
      :accept="accept.join()"
      :class="{ hide: fileList.length >= limit }"
      :disabled="disabled"
    >
      <el-button type="primary" icon="Plus" v-if="listType == 'text'" :disabled="disabled">点击上传文件</el-button>
      <el-button type="primary" icon="Plus" v-if="listType == 'picture'" :disabled="disabled">点击上传图片</el-button>
      <el-icon class="avatar-uploader-icon" v-if="listType == 'picture-card'"><plus /></el-icon>
      <template #tip>
        <div class="el-upload__tip">格式为:{{ fileType.join('/') }},大小不超过{{ fileSize }}MB,最多上传{{ limit }}个</div>
      </template>
    </el-upload>
  </div>
</template>
<script setup name="ImageFileUpload">
import { sysUpload, sysUploadDel } from '@/api/login.js';
import { ElMessageBox } from 'element-plus';

const props = defineProps({
  // 图片数组值
  saveFileArr: {
    type: Array,
    default: () => [],
  },
  // 文件列表的类型 'text' | 'picture' | 'picture-card'
  listType: {
    type: String,
    default: 'picture',
  },
  // 图片数量限制
  limit: {
    type: Number,
    default: 3,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 1000,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ['jpg', 'png', 'jpeg', 'svg', 'gif'],
  },
  // 关联类型和字段
  refField: {
    type: String,
    default: 'picXG',
  },
  refType: {
    type: String,
    default: 'picXG',
  },
  disabled: {
    type: Boolean,
    default: false,
  },
});
const { proxy } = getCurrentInstance();
const emit = defineEmits();
const fileList = ref([]);
const uploadList = ref([]);

// 图片上传
const handleChange = file => {
  // console.log('图片上传--', file);
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
      fileList.value.pop(); //删除失败的
      return false;
    }
  }
  if (file.name.length > 50) {
    proxy.$modal.msgError(`文件名称过长(50个字符以内),请先修改再上传!`);
    fileList.value.pop(); //删除失败的
    return false;
  }
  proxy.$modal.loading('正在上传,请稍候...');
  let formData = new FormData();
  formData.append('file', file.raw);
  sysUpload(formData).then(res => {
    if (res.code == 200) {
      let datas = res.data;
      datas.refField = props.refField; //关联字段
      datas.refType = props.refType; //关联类型
      uploadList.value.push(datas);
      props.saveFileArr.push(datas);
      // 文件状态改为上传成功
      fileList.value.map(item => (item.status = 'success'));
    } else {
      fileList.value.pop(); //删除失败的
      proxy.$modal.msgError('上传失败');
      proxy.$modal.closeLoading();
    }
    proxy.$modal.closeLoading();
  });
};
// 图片删除
const handleRemove = file => {
  // console.log('图片删除--', file);
  let fileIndex = null;
  uploadList.value.map((item, index) => {
    if (file.name == item.originalName || file.originalName == item.originalName) {
      fileIndex = index;
    }
  });
  // id为空时做逻辑删除,不调用删除接口
  let id = uploadList.value[fileIndex].id;
  if (!!!id) {
    uploadList.value.splice(fileIndex, 1);
    props.saveFileArr.splice(fileIndex, 1);
  } else {
    let ids = [];
    ids.push(id);
    sysUploadDel(ids).then(res => {
      uploadList.value.splice(fileIndex, 1);
      props.saveFileArr.splice(fileIndex, 1);
    });
  }
};
// 文件方法预览
const handlePictureCardPreview = file => {
  // 新上传的文件
  let filenames = uploadList.value.find(item => file.name == item.originalName);
  // console.log(file, filenames);
  let fileUrl = (file.url && file.url.includes('blob')) || !!!file.url ? filenames.url : file.url;
  ElMessageBox.confirm(`预览、下载此文件:  ${file.name}?`).then(
    () => {
      // 1,Base64进行转码,http
      let b64Encoded = Base64.encode(fileUrl);
      // let baseUrl = 'https://server1.wh-nf.cn:8115/';
      window.open(`previewUrl/onlinePreview?url=` + encodeURIComponent(b64Encoded));
    },
    () => false
  );
};
// 上传的文件类型
const accept = computed(() => {
  if (props.fileType.length) {
    let data = [];
    data = props.fileType.map(val => {
      return `.${val}`;
    });
    return data;
  } else {
    return [];
  }
});
function editPic() {
  // console.log('修改时图片回显--', props.saveFileArr);
  // 修改时图片回显
  fileList.value = [];
  uploadList.value = [];
  props.saveFileArr.map(item => {
    let params = {
      id: item.id,
      name: item.name,
      originalName: item.originalName,
      status: 'success',
      url: item.url,
    };
    fileList.value.push(params);
    uploadList.value.push(params);
  });
}
watch(
  () => props.saveFileArr,
  () => {
    setTimeout(() => {
      editPic();
    });
  },
  { immediate: true }
);
onMounted(() => {});
onBeforeMount(() => {
  fileList.value = [];
  uploadList.value = [];
});
</script>
<style lang="scss">
@import '@/assets/styles/variables.module.scss';
.publicImgFileUpload {
  width: 100%;
  .hide .el-upload {
    display: none;
  }
  .el-upload {
    background-color: $mainColor1;
  }
  .el-upload--text {
    background: none !important;
    justify-content: left !important;
  }
  .el-upload-list--picture-card .el-upload-list__item-actions span + span {
    margin-left: 10px;
  }
  .el-upload__tip {
    color: #c6c6c6;
  }
  .el-upload-list--picture {
    display: flex;
    flex-wrap: wrap;
    .el-upload-list__item {
      width: 48%;
      margin-right: 5px;
      .el-upload-list__item-file-name {
        width: 65%;
      }
    }
  }
  .el-upload-list--text {
    .el-upload-list__item {
      border-top: 1px dashed #c6c6c6;
      background-color: $mainColor1;
      padding: 10px;
      margin-top: 10px;
      .el-upload-list__item-file-name {
        color: #fff;
      }
    }
  }
}
</style>