main.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // 通用工具函数
  2. const Utils = {
  3. // 格式化文件大小
  4. formatFileSize: function(bytes) {
  5. if (bytes === 0) return '0 Bytes';
  6. const k = 1024;
  7. const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  8. const i = Math.floor(Math.log(bytes) / Math.log(k));
  9. return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  10. },
  11. // 显示加载状态
  12. showLoading: function(element) {
  13. element.innerHTML = '<div class="loading">加载中...</div>';
  14. },
  15. // 显示错误信息
  16. showError: function(element, message) {
  17. element.innerHTML = `<div class="error">错误: ${message}</div>`;
  18. },
  19. // 发送 AJAX 请求
  20. ajax: function(url, methodOrOptions = {}) {
  21. let options = {};
  22. // 如果第二个参数是字符串,视为 HTTP method
  23. if (typeof methodOrOptions === 'string') {
  24. options = { method: methodOrOptions };
  25. } else {
  26. options = methodOrOptions;
  27. }
  28. return fetch(url, {
  29. method: 'GET',
  30. headers: {
  31. 'Content-Type': 'application/json',
  32. ...options.headers
  33. },
  34. ...options
  35. }).then(response => {
  36. if (!response.ok) {
  37. // 对于404错误,尝试解析JSON响应以获取更详细的错误信息
  38. if (response.status === 404) {
  39. return response.json().then(data => {
  40. throw new Error(data.error || `文件不存在 (${response.status})`);
  41. }).catch(() => {
  42. throw new Error(`文件不存在 (${response.status})`);
  43. });
  44. }
  45. // 尝试解析错误响应
  46. return response.json().then(data => {
  47. throw new Error(data.error || `HTTP ${response.status}: ${response.statusText}`);
  48. }).catch(() => {
  49. throw new Error(`HTTP ${response.status}: ${response.statusText}`);
  50. });
  51. }
  52. return response.json();
  53. });
  54. }
  55. };
  56. // 初始化页面
  57. document.addEventListener('DOMContentLoaded', function() {
  58. // 自动隐藏闪现消息
  59. const flashMessages = document.querySelectorAll('.flash-message');
  60. flashMessages.forEach(function(message) {
  61. setTimeout(function() {
  62. message.style.opacity = '0';
  63. setTimeout(function() {
  64. message.remove();
  65. }, 300);
  66. }, 5000);
  67. });
  68. });