upload.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /**
  2. * 上传公共方法
  3. */
  4. import uniAsync from "@/utils/uni-async.js"; // uni api async 化
  5. import {baseApiUrl} from './config.js'
  6. import store from '@/store/index.js'
  7. /**
  8. * 上传文件到服务器
  9. */
  10. const uploadToServer = async (tempFilePath) => {
  11. const temres = await uniAsync.uploadFile({
  12. url: baseApiUrl + "/public/upload",
  13. filePath: tempFilePath,
  14. name: "file",
  15. header: {
  16. Authorization: store.state.user.token,
  17. },
  18. });
  19. const res = JSON.parse(temres.data);
  20. if (res.code === 200) {
  21. return res.data;
  22. }
  23. };
  24. /**
  25. * 上传图片
  26. * count 同时上传张数 默认:1
  27. */
  28. export const uploadImg = async (count = 1) => {
  29. const { tempFilePaths } = await uniAsync.chooseImage({ count });
  30. uni.showLoading({
  31. title: "上传中...",
  32. });
  33. const uploadResArr = tempFilePaths.map((item) => {
  34. return uploadToServer(item);
  35. });
  36. return new Promise((resolve, reject) => {
  37. Promise.all(uploadResArr)
  38. .then((res) => {
  39. uni.hideLoading();
  40. const arr = res.map((item) => {
  41. return item;
  42. });
  43. resolve(arr);
  44. })
  45. .catch((res) => {
  46. uni.hideLoading();
  47. });
  48. });
  49. };