Bladeren bron

上传文件的路径,保存到数据库中

Gogs 9 maanden geleden
bovenliggende
commit
291e3e9d18
12 gewijzigde bestanden met toevoegingen van 328 en 0 verwijderingen
  1. 8 0
      .idea/.gitignore
  2. 21 0
      .idea/FlaskProject.iml
  3. 12 0
      .idea/dataSources.xml
  4. 13 0
      .idea/forwardedPorts.xml
  5. 6 0
      .idea/inspectionProfiles/profiles_settings.xml
  6. 6 0
      .idea/misc.xml
  7. 8 0
      .idea/modules.xml
  8. 7 0
      .idea/sqldialects.xml
  9. 6 0
      .idea/vcs.xml
  10. 18 0
      app.py
  11. 52 0
      file_uploader.py
  12. 171 0
      files.py

+ 8 - 0
.idea/.gitignore

@@ -0,0 +1,8 @@
+# 默认忽略的文件
+/shelf/
+/workspace.xml
+# 基于编辑器的 HTTP 客户端请求
+/httpRequests/
+# Datasource local storage ignored files
+/dataSources/
+/dataSources.local.xml

+ 21 - 0
.idea/FlaskProject.iml

@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module type="PYTHON_MODULE" version="4">
+  <component name="Flask">
+    <option name="enabled" value="true" />
+  </component>
+  <component name="NewModuleRootManager">
+    <content url="file://$MODULE_DIR$">
+      <excludeFolder url="file://$MODULE_DIR$/.venv" />
+    </content>
+    <orderEntry type="jdk" jdkName="Python 3.8 (FlaskProject)" jdkType="Python SDK" />
+    <orderEntry type="sourceFolder" forTests="false" />
+  </component>
+  <component name="TemplatesService">
+    <option name="TEMPLATE_CONFIGURATION" value="Jinja2" />
+    <option name="TEMPLATE_FOLDERS">
+      <list>
+        <option value="$MODULE_DIR$/templates" />
+      </list>
+    </option>
+  </component>
+</module>

+ 12 - 0
.idea/dataSources.xml

@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="DataSourceManagerImpl" format="xml" multifile-model="true">
+    <data-source source="LOCAL" name="@60.204.139.57" uuid="c6362484-1f75-406e-adf3-f4b04f0729d3">
+      <driver-ref>mysql.8</driver-ref>
+      <synchronize>true</synchronize>
+      <jdbc-driver>com.mysql.cj.jdbc.Driver</jdbc-driver>
+      <jdbc-url>jdbc:mysql://60.204.139.57:6003</jdbc-url>
+      <working-dir>$ProjectFileDir$</working-dir>
+    </data-source>
+  </component>
+</project>

+ 13 - 0
.idea/forwardedPorts.xml

@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="PortForwardingSettings">
+    <ports>
+      <entry key="5000">
+        <ForwardedPortInfo>
+          <option name="hostPort" value="5000" />
+          <option name="readOnly" value="false" />
+        </ForwardedPortInfo>
+      </entry>
+    </ports>
+  </component>
+</project>

+ 6 - 0
.idea/inspectionProfiles/profiles_settings.xml

@@ -0,0 +1,6 @@
+<component name="InspectionProjectProfileManager">
+  <settings>
+    <option name="USE_PROJECT_PROFILE" value="false" />
+    <version value="1.0" />
+  </settings>
+</component>

+ 6 - 0
.idea/misc.xml

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="Black">
+    <option name="sdkName" value="Python 3.8 (FlaskProject)" />
+  </component>
+</project>

+ 8 - 0
.idea/modules.xml

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ProjectModuleManager">
+    <modules>
+      <module fileurl="file://$PROJECT_DIR$/.idea/FlaskProject.iml" filepath="$PROJECT_DIR$/.idea/FlaskProject.iml" />
+    </modules>
+  </component>
+</project>

+ 7 - 0
.idea/sqldialects.xml

@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="SqlDialectMappings">
+    <file url="file://$PROJECT_DIR$/data.py" dialect="GenericSQL" />
+    <file url="file://$PROJECT_DIR$/files.py" dialect="GenericSQL" />
+  </component>
+</project>

+ 6 - 0
.idea/vcs.xml

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="VcsDirectoryMappings">
+    <mapping directory="$PROJECT_DIR$" vcs="Git" />
+  </component>
+</project>

+ 18 - 0
app.py

@@ -1,6 +1,8 @@
 # -*- coding: utf-8 -*-
 from flask import Flask, jsonify, request
 from data import *
+from files import *
+from file_uploader import upload_file  # 导入文件上传的函数
 
 # 初始化 Flask 应用
 app = Flask(__name__)
@@ -9,6 +11,10 @@ app = Flask(__name__)
 initialize_database()
 initialize_table()
 
+# 初始化数据库和表
+initialize_files_database()
+initialize_files_table()
+
 @app.route('/')
 def home():
     return "Welcome to the Fruit API!"
@@ -53,6 +59,18 @@ def delete_fruit():
         return jsonify({"error": str(e)}), 500
 
 
+
+# 上传文件接口
+@app.route('/upload', methods=['POST'])
+def upload():
+    return upload_file()  # 调用封装好的文件上传函数
+
+# 下载文件接口
+@app.route('/download/<filename>', methods=['GET'])
+def download_file(filename):
+    from flask import send_from_directory
+    return send_from_directory('uploads', filename)
+
 # 运行 Flask 应用
 if __name__ == '__main__':
     app.run(host='0.0.0.0', port=5000, debug=True)

+ 52 - 0
file_uploader.py

@@ -0,0 +1,52 @@
+# file_uploader.py
+import os
+from flask import request, jsonify
+
+from files import insert_url
+
+# 上传目录
+UPLOAD_FOLDER = 'uploads'
+if not os.path.exists(UPLOAD_FOLDER):
+    os.makedirs(UPLOAD_FOLDER)
+
+# 允许的文件扩展名
+ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'pdf','mp4'}
+
+
+def allowed_file(filename):
+    """检查文件类型是否允许"""
+    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
+
+
+def upload_file():
+    """处理文件上传"""
+    # 检查请求中是否有文件
+    if 'file' not in request.files:
+        return jsonify({'error': 'No file part'}), 400
+
+    file = request.files['file']
+
+    # 检查文件是否为空
+    if file.filename == '':
+        return jsonify({'error': 'No selected file'}), 400
+
+    # 检查文件是否符合要求
+    if file and allowed_file(file.filename):
+        # 保存文件到服务器
+        filename = os.path.join(UPLOAD_FOLDER, file.filename)
+        file.save(filename)
+
+        # 返回文件的下载链接
+        download_url = f'http://127.0.0.1:5000/download/{file.filename}'
+
+        if not download_url:
+            return jsonify({"error": "Missing name or origin"}), 400
+
+        try:
+            insert_url(download_url)
+        except Exception as e:
+            return jsonify({"error": str(e)}), 500
+
+        return jsonify({'message': 'File uploaded successfully', 'download_url': download_url}), 200
+
+    return jsonify({'error': 'File type not allowed'}), 400

+ 171 - 0
files.py

@@ -0,0 +1,171 @@
+# -*- coding: utf-8 -*-
+import mysql.connector
+from mysql.connector import Error
+
+# 配置数据库连接
+DB_CONFIG = {
+    'host': '60.204.139.57',
+    'user': 'root',
+    'password': '1',
+    'port': 6003,
+    'database': 'files'  # 替换为数据库名称
+}
+
+# 初始化数据库
+def initialize_files_database():
+    try:
+        # 连接 MySQL 服务器(不指定数据库)
+        connection = mysql.connector.connect(
+            host=DB_CONFIG['host'],
+            user=DB_CONFIG['user'],
+            password=DB_CONFIG['password'],
+            port=DB_CONFIG['port']
+        )
+
+        if connection.is_connected():
+            print("成功连接到 MySQL 服务器")
+            cursor = connection.cursor()
+
+            # 检查数据库是否存在
+            cursor.execute(f"SHOW DATABASES LIKE '{DB_CONFIG['database']}';")
+            result = cursor.fetchone()
+
+            if result:
+                print(f"数据库 {DB_CONFIG['database']} 已存在。")
+            else:
+                print(f"数据库 {DB_CONFIG['database']} 不存在,正在创建...")
+                cursor.execute(f"CREATE DATABASE {DB_CONFIG['database']};")
+                print(f"数据库 {DB_CONFIG['database']} 创建成功。")
+
+    except Error as err:
+        print(f"连接 MySQL 时发生错误:{err}")
+    finally:
+        if connection.is_connected():
+            cursor.close()
+            connection.close()
+            print("MySQL 服务器连接已关闭")
+
+# 初始化表
+def initialize_files_table(table_name=None):
+    if not table_name:
+        table_name = 'filePath'
+
+    # 验证表名是否合法(这里的规则可以根据你的需求做调整)
+    allowed_tables = ['fruit', 'filePath']  # 你可以在这里列出允许的表名
+    if table_name not in allowed_tables:
+        raise ValueError(f"不允许使用此表名:{table_name}")
+
+    try:
+        connection = mysql.connector.connect(**DB_CONFIG)
+        if connection.is_connected():
+            cursor = connection.cursor()
+
+            # 动态创建表
+            create_table_query = f'''
+                CREATE TABLE IF NOT EXISTS `{table_name}` (
+                    id INT AUTO_INCREMENT PRIMARY KEY,
+                    name VARCHAR(100)
+                )
+            '''
+
+            cursor.execute(create_table_query)
+            print(f"--- 创建 {table_name} 表 ---")
+    except Error as err:
+        print(f"初始化表时发生错误:{err}")
+    finally:
+        if connection.is_connected():
+            cursor.close()
+            connection.close()
+            print("MySQL 连接已关闭")
+
+# 插入数据
+def insert_url(name):
+    try:
+        connection = mysql.connector.connect(**DB_CONFIG)
+        if connection.is_connected():
+            cursor = connection.cursor()
+
+            # 插入数据
+            cursor.execute("INSERT INTO filePath (name) VALUES (%s)", (name,))
+            connection.commit()
+            print(f"插入数据成功:({name})")
+    except Error as err:
+        print(f"插入数据时发生错误:{err}")
+    finally:
+        if connection.is_connected():
+            cursor.close()
+            connection.close()
+            print("MySQL 连接已关闭")
+
+# 插入数据
+def insert_data(name, origin):
+    try:
+        connection = mysql.connector.connect(**DB_CONFIG)
+        if connection.is_connected():
+            cursor = connection.cursor()
+
+            # 插入数据
+            cursor.execute("INSERT INTO filePath (name, origin) VALUES (%s, %s)", (name, origin))
+            connection.commit()
+            print(f"插入数据成功:({name}, {origin})")
+    except Error as err:
+        print(f"插入数据时发生错误:{err}")
+    finally:
+        if connection.is_connected():
+            cursor.close()
+            connection.close()
+            print("MySQL 连接已关闭")
+
+def delete_data(name):
+    try:
+        connection = mysql.connector.connect(**DB_CONFIG)
+        if connection.is_connected():
+            cursor = connection.cursor()
+
+            # 删除数据
+            cursor.execute("DELETE FROM filePath WHERE name = %s", (name,))
+            connection.commit()
+            print(f"成功删除名称为 {name} 的记录")
+    except Error as err:
+        print(f"删除数据时发生错误:{err}")
+    finally:
+        if connection.is_connected():
+            cursor.close()
+            connection.close()
+            print("MySQL 连接已关闭")
+
+
+# 查询数据
+def fetch_data():
+    try:
+        connection = mysql.connector.connect(**DB_CONFIG)
+        if connection.is_connected():
+            cursor = connection.cursor()
+
+            # 查询数据
+            cursor.execute("SELECT * FROM filePath")
+            rows = cursor.fetchall()
+            print("--- 查询结果 ---")
+            for row in rows:
+                print(row)
+            return rows
+    except Error as err:
+        print(f"查询数据时发生错误:{err}")
+    finally:
+        if connection.is_connected():
+            cursor.close()
+            connection.close()
+            print("MySQL 连接已关闭")
+
+# 主函数
+if __name__ == "__main__":
+    # 初始化数据库和表
+    initialize_files_database()
+    initialize_files_table()
+
+    # 插入示例数据
+    insert_data('Apple', 'China')
+    insert_data('Banana', 'Ecuador')
+
+    # 查询数据
+    fetch_data()