upload.js 2.4 KB

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