upload.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. import CryptoJS from './crypto.js'
  8. /**
  9. * 上传文件到服务器
  10. */
  11. export const uploadToServer = async (tempFilePath) => {
  12. const { envVersion } = uni.getAccountInfoSync().miniProgram
  13. const temres = await uniAsync.uploadFile({
  14. url: baseApiUrl + "/public/upload",
  15. filePath: tempFilePath,
  16. name: "file",
  17. header: {
  18. Authorization: store.state.user.token,
  19. },
  20. });
  21. const res = envVersion === 'release' ? JSON.parse(CryptoJS.Des3Decrypt(temres.data)) : JSON.parse(temres.data);
  22. if (res.code === 200) {
  23. return res.data;
  24. }
  25. };
  26. /**
  27. *
  28. * 上传回复音频到服务器
  29. */
  30. export const uploadAudioToServer = async(tempFilePath)=>{
  31. const { envVersion } = uni.getAccountInfoSync().miniProgram
  32. const temres = await uniAsync.uploadFile({
  33. url: baseApiUrl + "/community/question/reply/upload_audio",
  34. filePath: tempFilePath,
  35. name: "file",
  36. header: {
  37. Authorization: store.state.user.token,
  38. },
  39. });
  40. const res = envVersion === 'release' ? JSON.parse(CryptoJS.Des3Decrypt(temres.data)) : JSON.parse(temres.data);
  41. return res;
  42. }
  43. /**
  44. * 上传图片
  45. * count 同时上传张数 默认:1
  46. */
  47. export const uploadImg = async (count = 1) => {
  48. const { tempFilePaths } = await uniAsync.chooseImage({ count });
  49. uni.showLoading({
  50. title: "上传中...",
  51. });
  52. const uploadResArr = tempFilePaths.map((item) => {
  53. return uploadToServer(item);
  54. });
  55. return new Promise((resolve, reject) => {
  56. Promise.all(uploadResArr)
  57. .then((res) => {
  58. uni.hideLoading();
  59. const arr = res.map((item) => {
  60. return item;
  61. });
  62. resolve(arr);
  63. })
  64. .catch((res) => {
  65. uni.hideLoading();
  66. });
  67. });
  68. };