upload.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import { ElMessage } from "element-plus";
  2. import { computed, ref, watchEffect } from "vue";
  3. import mime from "mime";
  4. export type UploadProps<T> = {
  5. maxSize: number;
  6. formats: string[];
  7. upload?: (
  8. file: File,
  9. onPercentage: (percentage: number) => void
  10. ) => Promise<T>;
  11. };
  12. const defaultUpload = (
  13. file: File,
  14. onPercentage: (percentage: number) => void
  15. ) => {
  16. onPercentage(100);
  17. };
  18. export const useUpload = <T>(props: UploadProps<T>) => {
  19. const percentage = ref<number>();
  20. const size = computed(() => Math.floor(props.maxSize / 1024 / 1024) + "M");
  21. const format = computed(
  22. () =>
  23. `${props.formats.join("、")}${
  24. props.formats.length > 1 ? "等" : ""
  25. }格式的文件`
  26. );
  27. const accept = computed(() =>
  28. props.formats
  29. .map((format) => {
  30. // const index = format.indexOf(".");
  31. // const ext = ~index ? format.substring(index + 1) : format;
  32. // const extMime = mime.getType(ext);
  33. // return (extMime.substring(0, extMime.indexOf("/") + 1) + ext) as string;
  34. return format;
  35. })
  36. .join(", ")
  37. );
  38. console.log(accept);
  39. const fileRef = ref<File>();
  40. (window as any).fileRef = fileRef;
  41. const removeFile = () => {
  42. fileRef.value = undefined;
  43. return true;
  44. };
  45. const previewFile = () => {
  46. fileRef.value && window.open(URL.createObjectURL(fileRef.value));
  47. };
  48. const upload = async (file: File) => {
  49. const fileType = file.name
  50. .substring(file.name.lastIndexOf("."))
  51. .toUpperCase();
  52. if (!props.formats.some((type) => type.toUpperCase() === fileType)) {
  53. ElMessage.error(`请上传${format.value}`);
  54. return false;
  55. } else if (file.size > props.maxSize) {
  56. ElMessage.error(`请上传${size.value}以内的文件`);
  57. return false;
  58. } else {
  59. fileRef.value = file;
  60. await (props.upload || defaultUpload)(
  61. file,
  62. (val) => (percentage.value = val)
  63. );
  64. if (fileType === ".RAW") {
  65. }
  66. percentage.value = undefined;
  67. return true;
  68. }
  69. };
  70. return {
  71. file: fileRef,
  72. fileList: computed(() => (fileRef.value ? [fileRef.value] : [])),
  73. previewFile,
  74. removeFile,
  75. percentage,
  76. size,
  77. format,
  78. accept,
  79. upload,
  80. };
  81. };