Gogs 9 місяців тому
батько
коміт
81d511c432
2 змінених файлів з 82 додано та 7 видалено
  1. 37 2
      app.py
  2. 45 5
      templates/index.html

+ 37 - 2
app.py

@@ -18,6 +18,38 @@ app = Flask(__name__)
 @app.route('/')
 def home():
     return render_template('index.html')
+# 获取类别数据
+@app.route('/categories')
+def get_categories():
+    rows = fetch_data('category')
+
+    # 将查询结果格式化为字典列表
+    category_list = [{"id": row[0], "categoryName": row[1]} for row in rows]
+    print(category_list)
+    # 返回 JSON 格式的数据
+    return jsonify(category_list)
+
+@app.route('/category-data', methods=['GET'])
+def get_table():
+    # 获取查询参数中的表名 (categoryName)
+    category_name = request.args.get('categoryName')
+
+    if not category_name:
+        return jsonify({"error": "No categoryName provided"}), 400  # 如果没有提供表名,返回错误
+
+    # 根据表名查询数据
+    rows = fetch_data(category_name)
+
+    if not rows:
+        return jsonify({"error": f"No data found for table {category_name}"}), 404  # 如果没有找到数据,返回错误
+
+    # 将查询结果格式化为字典列表
+    category_list = [{"id": row[0], "categoryName": row[1], "url":row[2]} for row in rows]
+    print(category_list)
+
+    # 返回 JSON 格式的数据
+    return jsonify(category_list)
+
 
 # 添加水果数据
 @app.route('/add_fruit', methods=['POST'])
@@ -66,10 +98,13 @@ def upload():
     return upload_file()  # 调用封装好的文件上传函数
 
 # 下载文件接口
+from flask import send_from_directory
+
 @app.route('/download/<filename>', methods=['GET'])
 def download_file(filename):
-    from flask import send_from_directory
-    return send_from_directory('../uploads', filename)
+    # 强制下载文件
+    return send_from_directory('../uploads', filename, as_attachment=True)
+
 
 # 运行 Flask 应用
 if __name__ == '__main__':

+ 45 - 5
templates/index.html

@@ -15,15 +15,14 @@
             categoryList.innerHTML = '';
             categories.forEach(category => {
                 const listItem = document.createElement('li');
-                listItem.textContent = category.name;
-                listItem.onclick = () => fetchTableData(category.table_name);
+                listItem.textContent = category.categoryName;
+                listItem.onclick = () => fetchTableData(category.categoryName);
                 categoryList.appendChild(listItem);
             });
         }
 
-        // Fetch table data when a category is clicked
         async function fetchTableData(tableName) {
-            const response = await fetch(`/table-data?table=${tableName}`); // Backend endpoint for table data
+            const response = await fetch(`/category-data?categoryName=${tableName}`); // Backend endpoint for table data
             const tableData = await response.json();
             const tableBody = document.getElementById('table-body');
 
@@ -31,15 +30,56 @@
             tableBody.innerHTML = '';
             tableData.forEach(row => {
                 const tableRow = document.createElement('tr');
-                Object.values(row).forEach(value => {
+                Object.values(row).forEach((value) => {
                     const cell = document.createElement('td');
                     cell.textContent = value;
                     tableRow.appendChild(cell);
                 });
+
+                // Add the download button in the last column
+                const downloadCell = document.createElement('td');
+                const downloadButton = document.createElement('button');
+
+                downloadButton.textContent = 'Download';
+                downloadButton.onclick = () => downloadFile(row.categoryName); // Assuming row[1] is the filename
+                downloadCell.appendChild(downloadButton);
+                tableRow.appendChild(downloadCell);
+
                 tableBody.appendChild(tableRow);
             });
         }
 
+        async function downloadFile(filename) {
+            const response = await fetch(`/download/${filename}`, {
+                method: 'GET',
+                headers: {
+                    'Content-Type': 'application/json'
+                }
+            });
+
+            if (response.ok) {
+                // Create a blob from the response
+                const blob = await response.blob();
+
+                // Create a link element
+                const link = document.createElement('a');
+                link.href = URL.createObjectURL(blob);
+                link.download = filename;
+
+                // Append the link to the body (it needs to be in the DOM to work)
+                document.body.appendChild(link);
+
+                // Programmatically trigger the download
+                link.click();
+
+                // Clean up the DOM
+                document.body.removeChild(link);
+            } else {
+                console.error('Failed to download the file');
+            }
+        }
+
+
         // Initial load
         document.addEventListener('DOMContentLoaded', fetchCategories);
     </script>