初次提交

This commit is contained in:
2025-10-14 20:05:29 +08:00
commit 6e4e48fdd2
673 changed files with 437006 additions and 0 deletions

227
backend/demo_file_hash.py Normal file
View File

@@ -0,0 +1,227 @@
#!/usr/bin/env python3
"""
演示文件哈希原理和还原功能的脚本
"""
import hashlib
import requests
import os
# API基础URL
BASE_URL = "http://localhost:8000/api/v1"
USER_ID = 8
def calculate_sha256_hash(file_content: bytes) -> str:
"""计算文件的SHA-256哈希值"""
return hashlib.sha256(file_content).hexdigest()
def upload_test_file_with_hash():
"""上传测试文件并展示哈希计算过程"""
# 创建测试文件内容
original_content = "Hello World! 这是演示文件哈希的测试内容。\n包含中文和English混合内容。"
print(f"📄 原始文件内容:")
print(f"'{original_content}'")
print(f"📏 文件大小: {len(original_content.encode('utf-8'))} bytes")
print()
# 计算哈希值
file_hash = calculate_sha256_hash(original_content.encode('utf-8'))
print(f"🔒 计算SHA-256哈希值:")
print(f"{file_hash}")
print()
# 上传文件
try:
files = {
"file": ("demo_hash_test.txt", original_content.encode('utf-8'), "text/plain")
}
data = {
"user_id": USER_ID,
"description": "演示文件哈希功能",
"tags": "demo,hash,test",
"is_public": "false"
}
response = requests.post(
f"{BASE_URL}/files/upload",
files=files,
data=data
)
if response.status_code == 201:
result = response.json()
if result.get("success"):
file_info = result["data"]["file"]
server_hash = file_info["file_hash"]
file_id = file_info["id"]
print(f"✅ 文件上传成功!")
print(f"📋 文件ID: {file_id}")
print(f"📁 服务器存储的文件名: {file_info['filename']}")
print(f"🔒 服务器计算的哈希值: {server_hash}")
print()
# 验证哈希值一致性
if file_hash == server_hash:
print(f"✅ 哈希值验证通过! 客户端和服务器计算结果一致")
else:
print(f"❌ 哈希值验证失败! 客户端和服务器计算结果不一致")
print(f" 客户端: {file_hash}")
print(f" 服务器: {server_hash}")
return file_id, original_content, file_hash
else:
print(f"❌ 上传失败: {response.text}")
return None, None, None
except Exception as e:
print(f"❌ 上传出错: {e}")
return None, None, None
def download_and_verify_file(file_id: int, original_content: str, original_hash: str):
"""下载文件并验证完整性"""
print(f"\n📥 开始下载和验证文件...")
try:
# 下载文件
data = {
"user_id": USER_ID,
"file_id": file_id
}
response = requests.post(
f"{BASE_URL}/files/download",
json=data
)
if response.status_code == 200:
downloaded_content = response.content.decode('utf-8')
print(f"📄 下载的文件内容:")
print(f"'{downloaded_content}'")
print()
# 验证内容完整性
if downloaded_content == original_content:
print(f"✅ 文件内容完整性验证通过!")
else:
print(f"❌ 文件内容完整性验证失败!")
print(f" 原始内容: '{original_content}'")
print(f" 下载内容: '{downloaded_content}'")
# 计算下载文件的哈希值
downloaded_hash = calculate_sha256_hash(downloaded_content.encode('utf-8'))
print(f"🔒 下载文件的哈希值:")
print(f"{downloaded_hash}")
print()
# 验证哈希值
if downloaded_hash == original_hash:
print(f"✅ 下载文件哈希验证通过! 文件完整性得到保证")
else:
print(f"❌ 下载文件哈希验证失败! 文件可能已损坏")
print(f" 原始哈希: {original_hash}")
print(f" 下载哈希: {downloaded_hash}")
else:
print(f"❌ 下载失败: {response.text}")
except Exception as e:
print(f"❌ 下载过程出错: {e}")
def demonstrate_file_duplication():
"""演示文件去重功能"""
print(f"\n🔄 演示文件去重功能...")
print(f"尝试上传相同内容的文件,系统应该拒绝重复上传...")
# 创建与之前相同内容的文件
duplicate_content = "Hello World! 这是演示文件哈希的测试内容。\n包含中文和English混合内容。"
try:
files = {
"file": ("duplicate_file.txt", duplicate_content.encode('utf-8'), "text/plain")
}
data = {
"user_id": USER_ID,
"description": "重复文件测试",
"tags": "duplicate,test",
"is_public": "false"
}
response = requests.post(
f"{BASE_URL}/files/upload",
files=files,
data=data
)
if response.status_code == 409: # 409 Conflict 表示文件已存在
result = response.json()
print(f"✅ 文件去重功能正常工作!")
print(f"📋 系统检测到文件已存在,拒绝重复上传")
print(f"📄 原始文件名: {result.get('detail', {}).get('filename', 'Unknown')}")
elif response.status_code == 201:
print(f"⚠️ 文件去重功能可能未正常工作,重复上传成功了")
else:
print(f"❌ 测试失败: {response.text}")
except Exception as e:
print(f"❌ 测试过程出错: {e}")
def show_file_location_on_server():
"""显示文件在服务器上的存储位置"""
print(f"\n📁 文件在服务器上的存储位置:")
print(f"后端上传目录: backend/uploads/")
# 列出uploads目录中的文件
try:
if os.path.exists("backend/uploads"):
files = os.listdir("backend/uploads")
if files:
print(f"当前存储的文件:")
for file in files:
file_path = os.path.join("backend/uploads", file)
file_size = os.path.getsize(file_path)
print(f" 📄 {file} ({file_size} bytes)")
# 计算并显示文件的哈希值
with open(file_path, 'rb') as f:
content = f.read()
file_hash = calculate_sha256_hash(content)
print(f" 🔒 SHA-256: {file_hash}")
else:
print(f" (目录为空)")
else:
print(f" (uploads目录不存在)")
except Exception as e:
print(f" 无法读取目录: {e}")
if __name__ == "__main__":
print("🔐 文件哈希原理演示")
print("=" * 50)
# 1. 上传测试文件
file_id, original_content, original_hash = upload_test_file_with_hash()
if file_id:
# 2. 下载并验证文件
download_and_verify_file(file_id, original_content, original_hash)
# 3. 演示文件去重
demonstrate_file_duplication()
# 4. 显示文件存储位置
show_file_location_on_server()
print(f"\n🎉 演示完成!")
print(f"📚 关键知识点:")
print(f" • SHA-256哈希值用于验证文件完整性")
print(f" • 相同内容的文件具有相同的哈希值")
print(f" • 系统通过哈希值检测重复文件")
print(f" • 文件在上传、存储、下载过程中保持完整性")
else:
print(f"\n❌ 演示失败,无法上传测试文件")