upload.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import useStores from "@/store/modules/user.js";
  2. import config from "@/config";
  3. import { getToken } from "@/utils/auth";
  4. import modal from "@/plugins/modal";
  5. import common from "@/plugins/common";
  6. let timeout = 10000;
  7. const baseUrl = config.baseUrl;
  8. const upload = (config) => {
  9. const useStore = useStores();
  10. // 是否需要设置 token
  11. const isToken = (config.headers || {}).isToken === false;
  12. config.header = config.header || {};
  13. if (getToken() && !isToken) {
  14. config.header["Authorization"] = getToken();
  15. }
  16. // get请求映射params参数
  17. if (config.params) {
  18. let url = config.url + "?" + common.tansParams(config.params);
  19. url = url.slice(0, -1);
  20. config.url = url;
  21. }
  22. return new Promise((resolve, reject) => {
  23. uni.uploadFile({
  24. timeout: config.timeout || timeout,
  25. url: baseUrl + config.url,
  26. filePath: config.filePath,
  27. name: config.name || "file",
  28. header: config.header,
  29. formData: config.formData,
  30. success: (res) => {
  31. let result = JSON.parse(res.data);
  32. const code = result.code || 200;
  33. if (code === 200) {
  34. resolve(result);
  35. } else if (code == 401) {
  36. modal.confirm("登录状态已过期,您可以继续留在该页面,或者重新登录?").then((res) => {
  37. if (res) {
  38. useStore.LogOut().then((res) => {
  39. uni.reLaunch({ url: "/pages/login" });
  40. });
  41. }
  42. });
  43. reject("无效的会话,或者会话已过期,请重新登录。");
  44. } else if (code === 500 || res.statusCode === 500) {
  45. if (res.data.msg.indexOf(":") !== -1) {
  46. modal.msg(res.data.msg.split(":")[1]);
  47. reject(res.data.msg.split(":")[1]);
  48. } else {
  49. modal.msg(res.data.msg);
  50. reject(res.data.msg);
  51. }
  52. } else if (code !== 200 && code !== "0") {
  53. reject(code);
  54. }
  55. },
  56. fail: (error) => {
  57. let { message } = error;
  58. if (message == "Network Error") {
  59. message = "后端接口连接异常";
  60. } else if (message.includes("timeout")) {
  61. message = "系统接口请求超时";
  62. } else if (message.includes("Request failed with status code")) {
  63. message = "系统接口" + message.substr(message.length - 3) + "异常";
  64. }
  65. reject(error);
  66. },
  67. });
  68. });
  69. };
  70. export default upload;