|
发表于 2025-8-12 14:48:05
|
显示全部楼层
在 Python 的 `http.server` 默认配置下,浏览器无法直接下载整个目录(含子目录结构)。以下是符合你需求的解决方案:
### 解决方案:打包目录为 ZIP 文件(不压缩)
虽然你要求不压缩,但浏览器无法直接下载文件夹结构。最接近的方式是**将目录打包为 ZIP 文件(使用存储模式不压缩)**,用户下载后解压即可得到原始文件结构。
#### 操作步骤:
1. 使用此自定义 Python 脚本启动服务器(保存为 `server.py`):
- import http.server
- import socketserver
- import os
- import zipfile
- from io import BytesIO
- PORT = 8000
- class CustomHandler(http.server.SimpleHTTPRequestHandler):
- def do_GET(self):
- if self.path == '/download':
- # 打包当前目录(不压缩)
- buffer = BytesIO()
- with zipfile.ZipFile(buffer, 'w', zipfile.ZIP_STORED) as zipf:
- for root, dirs, files in os.walk('.'):
- for file in files:
- path = os.path.join(root, file)
- zipf.write(path, os.path.relpath(path))
-
- self.send_response(200)
- self.send_header('Content-Type', 'application/zip')
- self.send_header('Content-Disposition', 'attachment; filename="folder.zip"')
- self.end_headers()
- buffer.seek(0)
- self.wfile.write(buffer.getvalue())
- else:
- super().do_GET()
- with socketserver.TCPServer(("", PORT), CustomHandler) as httpd:
- print(f"服务器已启动,访问 http://localhost:{PORT}")
- print("下载整个目录: http://localhost:8000/download")
- httpd.serve_forever()
复制代码
2. **启动服务器**(在要共享的目录中运行):
3. 在浏览器访问:
- 浏览文件:`http://<服务器IP>:8000`
- **下载整个目录**:`http://<服务器IP>:8000/download`
---
### 关键说明:
1. **ZIP_STORED 模式**:文件仅打包不压缩,速度极快,解压后得到原始文件
2. **目录结构保留**:子目录和文件名保持不变
3. **无需额外软件**:浏览器直接下载 ZIP,系统自带解压功能
---
### 替代方案(命令行下载)
如果客户端能使用命令行工具:
- # 在客户端执行(替换IP为服务器IP)
- wget -r -nH --cut-dirs=1 http://<服务器IP>:8000/
复制代码
参数说明:
- `-r`:递归下载
- `-nH`:不创建主机名前缀
- `--cut-dirs=1`:忽略服务器路径层级
---
### 多线程下载说明
Python 的 `http.server` 默认单线程,如需多线程支持:
- # 替换 TCPServer 为 ThreadingHTTPServer
- from http.server import ThreadingHTTPServer
- httpd = ThreadingHTTPServer(("", PORT), CustomHandler)
复制代码
这样可同时处理多个客户端请求(但单个文件下载仍受限于网络带宽)。
> 提示:大文件下载建议用专业工具(如 rsync),HTTP 协议本身不支持断点续传目录。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|