file.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. function basename(path) {
  2. if (!path) return "";
  3. const normalized = String(path).replace(/\\/g, "/");
  4. const idx = normalized.lastIndexOf("/");
  5. return idx >= 0 ? normalized.slice(idx + 1) : normalized;
  6. }
  7. /**
  8. * 上传单个文件到统一文件服务
  9. * POST /main/file/uploadFile?module=...
  10. * 表单字段名:multiPartFile
  11. *
  12. * 选图后立刻调用此接口,调用方负责在 UI 上跟踪每张图的状态。
  13. */
  14. export function uploadAttachment(filePath, moduleName = "hr_attendance") {
  15. const uploadUrl = `${Vue.prototype.apiUrl}/main/file/uploadFile?module=${encodeURIComponent(
  16. moduleName
  17. )}`;
  18. return new Promise((resolve, reject) => {
  19. if (!filePath) {
  20. reject(new Error("缺少文件路径"));
  21. return;
  22. }
  23. const token = uni.getStorageSync("token");
  24. const userInfo = uni.getStorageSync("userInfo") || {};
  25. uni.uploadFile({
  26. url: uploadUrl,
  27. filePath,
  28. name: "multiPartFile",
  29. header: token
  30. ? {
  31. "zoomwin-token": token,
  32. Authorization: token,
  33. "zoomwin-sid": userInfo.sessionId || "",
  34. }
  35. : { platform: "wxapp" },
  36. success: (response) => {
  37. let body = response.data;
  38. if (typeof body === "string") {
  39. try {
  40. body = JSON.parse(body);
  41. } catch (error) {
  42. reject(new Error("文件上传响应解析失败"));
  43. return;
  44. }
  45. }
  46. if (response.statusCode < 200 || response.statusCode >= 300) {
  47. reject(new Error((body && body.message) || `文件上传失败(${response.statusCode})`));
  48. return;
  49. }
  50. if (body && body.code !== undefined && Number(body.code) !== 0) {
  51. reject(new Error(body.message || "文件上传失败"));
  52. return;
  53. }
  54. const data = body && body.data;
  55. if (!data || data.id === undefined || data.id === null) {
  56. reject(new Error("文件上传响应缺少主键"));
  57. return;
  58. }
  59. resolve(data);
  60. },
  61. fail: (error) => reject(new Error(error.errMsg || "文件上传失败")),
  62. });
  63. });
  64. }
  65. export { basename as attachmentBasename };