DragUpload.vue 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <template>
  2. <div>
  3. <lay-upload :url="uploadUrl" :drag="true" :status="status" :headers="headers" :beforeUpload="handleBeforeUpload" @done="handleUploadDone" @error="handleUploadError" />
  4. <div>
  5. <div class="status_wp">
  6. <lay-space>
  7. <span>{{ fileName }}</span>
  8. <lay-icon v-if="status == 1" class="layui-anim layui-anim-rotate layui-anim-loop" type="layui-icon-loading" />
  9. <lay-icon v-if="status == 2" class="success" type="layui-icon-success" />
  10. <lay-icon v-if="status == 3" class="error" type="layui-icon-error" />
  11. </lay-space>
  12. </div>
  13. </div>
  14. </div>
  15. </template>
  16. <script lang="ts" setup>
  17. import { ref, watch, getCurrentInstance } from "vue";
  18. const { proxy }: any = getCurrentInstance();
  19. const emit = defineEmits();
  20. const props = defineProps({
  21. modelValue: String,
  22. status: Number,
  23. url: {
  24. type: String,
  25. default: `${import.meta.env.VITE_API_BASE_URL}/client/upload`,
  26. },
  27. beforeUpload: Function,
  28. uploadDone: Function,
  29. });
  30. watch(
  31. () => props.status,
  32. (value) => {
  33. updataStatus(value || 0);
  34. }
  35. );
  36. const status = ref(0);
  37. const fileName = ref();
  38. const uploadUrl = props.url;
  39. const headers = {
  40. auth: "4L",
  41. Token: window.sessionStorage.getItem("_4L_TOKEN") || "",
  42. };
  43. const uploadValue = ref();
  44. uploadValue.value = props.modelValue;
  45. // 上传前处理方法
  46. const handleBeforeUpload = (file: File) => {
  47. updataStatus(1);
  48. let isUpload = true;
  49. fileName.value = file.name;
  50. if (typeof props.beforeUpload === "function")
  51. isUpload = props.beforeUpload(file, (value: number) => {
  52. updataStatus(value);
  53. });
  54. return isUpload;
  55. };
  56. // 上传结束回调
  57. const handleUploadDone = (e: any) => {
  58. let result = JSON.parse(e.data);
  59. if (JSON.parse(e.data).code != 200) {
  60. proxy.$message(`${result.msg}`, 2);
  61. return updataStatus(3);
  62. }
  63. emit("update:modelValue", JSON.parse(e.data).data);
  64. updataStatus(2);
  65. };
  66. // 上传失败回调
  67. const handleUploadError = () => {
  68. uploadValue.value = undefined;
  69. updataStatus(3);
  70. };
  71. const updataStatus = (value: number) => {
  72. status.value = value;
  73. };
  74. </script>
  75. <style lang="scss" scoped>
  76. .status_wp {
  77. .success {
  78. color: var(--primary-color);
  79. }
  80. .error {
  81. color: var(--danger-color);
  82. }
  83. }
  84. </style>