index.vue 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <template>
  2. <t-upload
  3. ref="uploadRef3"
  4. v-model="files"
  5. :theme="theme"
  6. :tips="`最多只能上传 ${imgLength} 张图片`"
  7. accept="image/*"
  8. :abridge-name="[6, 6]"
  9. :auto-upload="true"
  10. :upload-all-files-in-one-request="false"
  11. multiple
  12. :max="imgLength"
  13. :before-upload="handleBeforeUpload"
  14. :request-method="upload"
  15. @fail="handleFail"
  16. @change="handleChange"
  17. >
  18. </t-upload>
  19. </template>
  20. <script setup name="MyUpload">
  21. import { ref } from 'vue';
  22. import { MessagePlugin } from 'tdesign-vue-next';
  23. import { uploadFiles } from '@/api/common';
  24. import { getFileMD5 } from '@/utils/crypto';
  25. const emit = defineEmits(['change']);
  26. const props = defineProps({
  27. theme: {
  28. type: String,
  29. default: 'image',
  30. },
  31. accept: {
  32. type: String,
  33. default: '.jpg,.jpeg,.png',
  34. },
  35. imgLength: {
  36. type: Number,
  37. default: 3,
  38. },
  39. maxSize: {
  40. // 单位kb
  41. type: Number,
  42. default: 20 * 1024,
  43. },
  44. });
  45. const files = ref([]);
  46. const checkFileFormat = (fileType) => {
  47. const _file_format = '.' + fileType.split('.').pop().toLocaleLowerCase();
  48. return props.accept.split(',').includes(_file_format.toLocaleLowerCase());
  49. };
  50. const handleBeforeUpload = (file) => {
  51. if (file.size > props.maxSize * 1024) {
  52. const size =
  53. props.maxSize < 1024
  54. ? `${props.maxSize}kb`
  55. : `${Math.floor(props.maxSize / 1024)}M`;
  56. const content = '文件大小不能超过' + size;
  57. MessagePlugin.error(content);
  58. return false;
  59. }
  60. if (!checkFileFormat(file.name)) {
  61. const content = '只支持文件格式为' + props.accept;
  62. MessagePlugin.error(content);
  63. return false;
  64. }
  65. return true;
  66. };
  67. const handleFail = ({ file }) => {
  68. MessagePlugin.error(`文件 ${file.name} 上传失败`);
  69. };
  70. const upload = async (files) => {
  71. let formData = new FormData();
  72. const file = files[0].raw;
  73. const md5 = await getFileMD5(file);
  74. formData.append('file', file);
  75. formData.append('type', 'FILE');
  76. const res = await uploadFiles(formData, md5).catch(() => {});
  77. if (res) {
  78. return { status: 'success', response: { id: res.id, url: res.previewUrl } };
  79. } else {
  80. return { status: 'fail', error: '上传失败' };
  81. }
  82. };
  83. const handleChange = () => {
  84. emit(
  85. 'change',
  86. files.value.map((item) => item.response)
  87. );
  88. };
  89. </script>