index.ts 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. import { serviceURL } from "@/services/request";
  2. import { message } from "ant-design-vue";
  3. import { ref } from "vue";
  4. import { FileInfo, FileItem } from "./interface";
  5. function getBase64(file: File) {
  6. return new Promise((resolve, reject) => {
  7. const reader = new FileReader();
  8. reader.readAsDataURL(file);
  9. reader.onload = () => resolve(reader.result);
  10. reader.onerror = error => reject(error);
  11. });
  12. }
  13. function handleIsJSON(val: string) {
  14. try {
  15. const str = JSON.parse(val)
  16. return str
  17. } catch (e) {
  18. return val
  19. }
  20. }
  21. function getImg(imgURl: string) {
  22. let result = '';
  23. if (imgURl) {
  24. result = serviceURL.uploadUrl.replace('/upload', '') + imgURl.replace('./', '/');
  25. }
  26. return result;
  27. }
  28. function getImgName(value: string) {
  29. let result = '--'
  30. if (value) {
  31. // const str = JSON.parse(value).replace(/\"/g, "");
  32. const str = value.replace(/\"/g, "");
  33. const lastIndex = str.lastIndexOf('/') + 1;
  34. result = str.slice(lastIndex, str.length)
  35. }
  36. return result
  37. }
  38. export function handleUplodImg(limitSize = 1) {
  39. // 上传地址
  40. const uploadUrl = ref<string>('')
  41. // 图片列表
  42. const uploadImgList = ref<FileItem[]>([])
  43. /**
  44. * 获取上传地址,记住此方法需要在初始化数据加载完成(initData)之后 调用
  45. */
  46. function getUploadUrl() {
  47. uploadUrl.value = serviceURL.uploadUrl
  48. }
  49. /**
  50. * 上传图片变更
  51. * @param param0
  52. */
  53. function uploadChange({ file, fileList }: FileInfo) {
  54. let resFileList = [...fileList];
  55. // 1. Limit the number of uploaded files
  56. resFileList = resFileList.slice(-limitSize);
  57. // 2. 处理上传异常
  58. if (file.status !== 'uploading') {
  59. if (file.xhr?.status !== 200) {
  60. message.error(`服务器返回状态不为200: ${file.xhr?.statusText}`)
  61. }
  62. }
  63. if (file.status === 'done') {
  64. resFileList.forEach(el => {
  65. if (el.response) {
  66. el.name = el.response[0].fileName
  67. }
  68. })
  69. }
  70. uploadImgList.value = resFileList;
  71. return Promise.resolve(uploadImgList.value)
  72. }
  73. /**
  74. * 获取图片的filePath
  75. * @returns
  76. */
  77. function getUploadResultUrl(): string[] {
  78. const result: string[] = []
  79. uploadImgList.value.forEach(el => {
  80. if (Array.isArray(el.response)) {
  81. el.response.forEach(e => {
  82. result.push(e.filePath)
  83. })
  84. } else {
  85. console.warn('ant-design获取服务返回图片的数据发生变化,请在控制台查看')
  86. console.log(el)
  87. }
  88. })
  89. return result;
  90. }
  91. return { uploadUrl, uploadImgList, uploadChange, getUploadUrl, getUploadResultUrl }
  92. }
  93. /**
  94. * 预览图片
  95. */
  96. export function handlePreviewImg() {
  97. // 是否查看附件
  98. const previewVisible = ref<boolean>(false)
  99. // 预览图片地址
  100. const previewImage = ref<string | undefined>('');
  101. /**
  102. * 关闭查看图片
  103. */
  104. function cancelImg() {
  105. previewVisible.value = false;
  106. }
  107. /**
  108. * 预览图片
  109. */
  110. async function previewImg(file: FileItem | string) {
  111. if (typeof file === 'string') {
  112. if (file && file !== '--') {
  113. // 处理服务的脏数据,时而反而JSON格式,时而返回string格式,
  114. // fuck
  115. const temp = handleIsJSON(file).replace(/\"/g, "")
  116. previewImage.value = getImg(temp)
  117. previewVisible.value = true;
  118. }
  119. } else {
  120. if (!file.url && !file.preview) {
  121. file.preview = (await getBase64(file.originFileObj)) as string;
  122. }
  123. previewImage.value = file.url || file.preview;
  124. previewVisible.value = true;
  125. }
  126. }
  127. return { previewVisible, previewImage, cancelImg, previewImg, getImgName }
  128. }
  129. /**
  130. * 获取上传好的图片地址
  131. * @returns
  132. */
  133. export function getUploadImg() {
  134. // 存储上传的图片
  135. const imgs = ref<string[]>([])
  136. // 存储从服务获取的图片信息,用于展示
  137. const uploadImgList = ref<FileItem[]>([])
  138. // 上传图片
  139. function uploadImgAction(value: string[]) {
  140. imgs.value = value
  141. }
  142. // 用于处理从服务获取的图片
  143. function handleImg(value: string) {
  144. const arr = value.split(',')
  145. return arr.map((e, i) => {
  146. const str = handleIsJSON(e);
  147. return {
  148. uid: i.toString(),
  149. name: getImgName(e),
  150. url: getImg(str),
  151. };
  152. });
  153. }
  154. // 获取上传的第一张图片
  155. function getFirstImg() {
  156. return imgs.value.length ? imgs.value[0] : ''
  157. }
  158. return { imgs, uploadImgAction, uploadImgList, handleImg, getFirstImg }
  159. }