upload.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. percentage.value = undefined;
  65. return true;
  66. }
  67. };
  68. return {
  69. file: fileRef,
  70. fileList: computed(() => (fileRef.value ? [fileRef.value] : [])),
  71. previewFile,
  72. removeFile,
  73. percentage,
  74. size,
  75. format,
  76. accept,
  77. upload,
  78. };
  79. };