Procházet zdrojové kódy

文件上传下载,页面展示

Gogs před 9 měsíci
rodič
revize
d105120e7f
3 změnil soubory, kde provedl 137 přidání a 19 odebrání
  1. 37 12
      db_utils/files.py
  2. 28 2
      file_uploader.py
  3. 72 5
      templates/index.html

+ 37 - 12
db_utils/files.py

@@ -47,20 +47,19 @@ def initialize_files_database():
             connection.close()
             print("MySQL 服务器连接已关闭")
 
-# 初始化表
 def initialize_files_table(table_name = "category"):
     try:
         connection = mysql.connector.connect(**DB_CONFIG)
         if connection.is_connected():
             cursor = connection.cursor()
 
-            # 动态创建表
+            # 动态创建表,指定字符集为 utf8mb4
             create_table_query = f'''
                 CREATE TABLE IF NOT EXISTS `{table_name}` (
                     id INT AUTO_INCREMENT PRIMARY KEY,
-                    name VARCHAR(255),
-                    url VARCHAR(255)
-                )
+                    name VARCHAR(255) UNIQUE,
+                    url VARCHAR(255) UNIQUE
+                ) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci
             '''
 
             cursor.execute(create_table_query)
@@ -73,6 +72,7 @@ def initialize_files_table(table_name = "category"):
             connection.close()
             print("MySQL 连接已关闭")
 
+
 # 插入数据
 def insert_url(name, url, table_name="category"):
     try:
@@ -87,19 +87,43 @@ def insert_url(name, url, table_name="category"):
             insert_query = f"INSERT INTO `{table_name}` (name, url) VALUES (%s, %s)"
             cursor.execute(insert_query, (name, url))
             connection.commit()
-            print(f"插入文件数据成功:({name}, {url}) 到表 {table_name}")
+
+            # 判断插入是否成功
+            if cursor.rowcount > 0:
+                print(f"插入文件数据成功:({name}, {url}) 到表 {table_name}")
+                file_result = {"status": "success"}
+            else:
+                print(f"插入文件数据失败:({name}, {url}) 到表 {table_name}")
+                file_result = {"status": "failed"}
 
             # 确保 category 表存在
             initialize_files_table("category")
 
-            # 插入表名到 category 表
-            insert_query = "INSERT IGNORE INTO `category` (name) VALUES (%s)"
-            cursor.execute(insert_query, (table_name,))
-            connection.commit()
-            print(f"插入表名成功:({table_name}) 到表 category")
+            # 查询是否已经存在该表名
+            select_query = "SELECT * FROM `category` WHERE `name` = %s"
+            cursor.execute(select_query, (table_name,))
+            existing_category = cursor.fetchone()
 
-    except Error as err:
+            if existing_category:
+                print(f"表名 {table_name} 已经存在,不插入!")
+                category_result = {"status": "exists"}
+            else:
+                # 执行插入 category
+                insert_query = "INSERT INTO `category` (name) VALUES (%s)"
+                cursor.execute(insert_query, (table_name,))
+                connection.commit()
+                print(f"插入表名成功:({table_name}) 到表 category")
+                category_result = {"status": "success"}
+
+            return {"status": "success", "file_result": file_result, "category_result": category_result}
+
+    except mysql.connector.Error as err:
+        if err.errno == 1062:  # Duplicate entry error
+            print(f"文件 {name} 已存在,不重复插入。")
+            return {"status": "duplicate", "message": f"文件 {name} 已存在"}
         print(f"插入数据时发生错误:{err}")
+        return {"status": "error", "message": str(err)}
+
     finally:
         if connection.is_connected():
             cursor.close()
@@ -107,6 +131,7 @@ def insert_url(name, url, table_name="category"):
             print("MySQL 连接已关闭")
 
 
+
 # 查询数据
 def fetch_data(table_name):
     try:

+ 28 - 2
file_uploader.py

@@ -53,7 +53,8 @@ def upload_file():
                 return jsonify({'error': f'No table mapping for file type: {file_ext}'}), 400
 
             # 保存文件到服务器
-            filename = secure_filename(file.filename)
+            #filename = secure_filename(file.filename)  #格式化文件名
+            filename = file.filename
             file_path = os.path.join(UPLOAD_FOLDER, filename)
             file.save(file_path)
 
@@ -62,8 +63,32 @@ def upload_file():
 
             # 插入数据库
             try:
-                insert_url(filename,download_url, target_table)
+                result = insert_url(filename, download_url, target_table)
+                print("result:", result)  # 调试输出
+
+                if result.get("status") == "error":
+                    print("发生数据库错误:", result.get("message"))
+                    return jsonify({"error": f"Database error: {result.get('message')}"}), 500
+                else:
+                    # 文件插入结果
+                    if result.get("status") == "success":
+                        print("文件插入成功!")
+                    elif result.get("status") == "duplicate":
+                        print(f"文件 {filename} 已存在,不重复插入。")
+                        return jsonify({"message": f"文件 {filename} 已经存在"}), 409
+                    else:
+                        print("文件插入失败,返回结果:", result.get("file_result"))
+
+                    # 分类表插入结果
+                    if result.get("category_result") and result["category_result"].get("status") == "exists":
+                        print("表名已存在,无需插入。")
+                    elif result.get("category_result") and result["category_result"].get("status") == "success":
+                        print("表名插入成功!")
+                    else:
+                        print("分类表插入失败,返回结果:", result.get("category_result"))
+
             except Exception as e:
+                print("异常信息:", str(e))
                 return jsonify({"error": f"Database error: {str(e)}"}), 500
 
             return jsonify({'message': 'File uploaded successfully', 'download_url': download_url}), 200
@@ -72,3 +97,4 @@ def upload_file():
 
     except Exception as e:
         return jsonify({"error": f"Server error: {str(e)}"}), 500
+

+ 72 - 5
templates/index.html

@@ -30,7 +30,9 @@
             tableBody.innerHTML = '';
             tableData.forEach(row => {
                 const tableRow = document.createElement('tr');
-                Object.values(row).forEach((value) => {
+                // 显示 id 和 categoryName
+                const cells = [row.id, row.categoryName];
+                cells.forEach(value => {
                     const cell = document.createElement('td');
                     cell.textContent = value;
                     tableRow.appendChild(cell);
@@ -79,6 +81,29 @@
             }
         }
 
+        // Function to handle file upload
+        async function uploadFile() {
+            const fileInput = document.getElementById('file-input');
+            const file = fileInput.files[0]; // Get the selected file
+            const formData = new FormData();
+            formData.append('file', file);
+
+            const response = await fetch('/upload', {
+                method: 'POST',
+                body: formData,
+            });
+
+            if (response.ok) {
+                alert('File uploaded successfully!');
+                fetchCategories(); // Reload categories after upload
+            } else if (response.status === 409) {
+                // 处理文件已存在的情况
+                const data = await response.json();
+                alert(data.message); // 显示 "File already exists, no need to insert again."
+            } else {
+                alert('Failed to upload file');
+            }
+        }
 
         // Initial load
         document.addEventListener('DOMContentLoaded', fetchCategories);
@@ -95,6 +120,10 @@
             background-color: #f8f9fa;
             padding: 1em;
             border-right: 1px solid #ddd;
+            display: flex;
+            flex-direction: column;
+            justify-content: flex-start;
+            height: 100vh;
         }
 
         #content {
@@ -137,6 +166,36 @@
         th {
             background-color: #f1f1f1;
         }
+
+        /* Styling the upload section to be at the bottom of the sidebar */
+        #upload-section {
+            margin-top: auto;
+            padding: 10px;
+            background-color: #fff;
+            border: 1px solid #ddd;
+            border-radius: 5px;
+        }
+
+        #upload-section input[type="file"] {
+            width: calc(100% - 120px);
+            margin-right: 10px;
+            padding: 5px;
+            font-size: 16px;
+        }
+
+        #upload-section button {
+            padding: 8px 16px;
+            font-size: 16px;
+            background-color: #007bff;
+            color: white;
+            border: none;
+            border-radius: 5px;
+            cursor: pointer;
+        }
+
+        #upload-section button:hover {
+            background-color: #0056b3;
+        }
     </style>
 </head>
 <body>
@@ -145,19 +204,27 @@
         <ul id="category-list">
             <!-- Categories will be dynamically loaded here -->
         </ul>
+
+        <!-- File Upload Section (Now positioned at the bottom of the sidebar) -->
+        <div id="upload-section">
+            <h3>上传文件</h3>
+            <input type="file" id="file-input">
+            <button onclick="uploadFile()">上传</button>
+        </div>
     </div>
+
     <div id="content">
-        <h2>数据</h2>
+        <h2>文件列表</h2>
         <table>
             <thead>
                 <tr>
                     <th>ID</th>
-                    <th>名称</th>
-                    <th>URL</th>
+                    <th>Category Name</th>
+                    <th>操作</th>
                 </tr>
             </thead>
             <tbody id="table-body">
-                <!-- Table data will be dynamically loaded here -->
+                <!-- Data will be dynamically loaded here -->
             </tbody>
         </table>
     </div>