useImageUpload.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import { ref } from "vue";
  2. import { HTTP_REQUEST_URL, TOKENNAME } from "@/config/app.js";
  3. import { toLogin, checkLogin } from "@/libs/login";
  4. import { useAppStore } from "@/stores/app";
  5. import { useToast } from "@/hooks/useToast";
  6. export function useImageUpload(formData) {
  7. const imageList = ref([]);
  8. const appStore = useAppStore();
  9. const uploadLoading = ref(false);
  10. const { Toast } = useToast();
  11. // 上传单个文件
  12. const uploadFilePromise = (url) => {
  13. return new Promise((resolve, reject) => {
  14. uni.uploadFile({
  15. url: `${HTTP_REQUEST_URL}/api/front/user/upload/image`,
  16. filePath: url,
  17. name: "multipart",
  18. header: {
  19. [TOKENNAME]: appStore.tokenComputed,
  20. },
  21. formData,
  22. success: (res) => {
  23. // 兼容后端返回格式
  24. let data = res.data;
  25. if (typeof data === "string") {
  26. try {
  27. data = JSON.parse(data);
  28. } catch (e) {}
  29. }
  30. console.log("data", data);
  31. if (data?.code === 200) {
  32. resolve(data.data);
  33. } else {
  34. reject(data.data);
  35. }
  36. },
  37. fail: reject,
  38. });
  39. });
  40. };
  41. // 处理上传
  42. const afterRead = async (event) => {
  43. if (!appStore.tokenComputed && !checkLogin()) {
  44. toLogin();
  45. return Promise.reject({ msg: "未登录" });
  46. }
  47. uploadLoading.value = true;
  48. let lists = [].concat(event.file);
  49. let fileListLen = imageList.value.length;
  50. lists.forEach((item) => {
  51. imageList.value.push({
  52. ...item,
  53. status: "uploading",
  54. message: "上传中",
  55. });
  56. });
  57. // 逐个上传,每个都 try-catch,保证每个图片都能更新状态
  58. for (let i = 0; i < lists.length; i++) {
  59. const curIndex = fileListLen + i;
  60. try {
  61. const result = await uploadFilePromise(lists[i].url);
  62. imageList.value.splice(curIndex, 1, {
  63. ...imageList.value[curIndex],
  64. status: "success",
  65. message: "",
  66. info: result,
  67. });
  68. } catch (error) {
  69. imageList.value.splice(curIndex, 1, {
  70. ...imageList.value[curIndex],
  71. status: "failed",
  72. message: "上传失败",
  73. });
  74. }
  75. }
  76. uploadLoading.value = false;
  77. };
  78. // 删除图片
  79. const deletePic = (event) => {
  80. imageList.value.splice(event.index, 1);
  81. };
  82. return {
  83. uploadLoading,
  84. imageList,
  85. afterRead,
  86. deletePic,
  87. };
  88. }