nano server.py # 填写下面内容
sudo python server.py --port 80 运行这个 python 并且指定端口为 80
import os from http.server import BaseHTTPRequestHandler, HTTPServer import cgi import urllib.parse UPLOAD_DIR = '/home/eisc' class RequestHandler(BaseHTTPRequestHandler): def do_GET(self): """处理 GET 请求,展示目录和文件列表""" path = urllib.parse.unquote(self.path) if path == '/': path = '/' abs_path = os.path.join(UPLOAD_DIR, path.strip('/')) if os.path.isdir(abs_path): # 显示上传和下载页面以及目录列表 self.send_response(200) self.send_header('Content-type', 'text/html; charset=utf-8') self.end_headers() # 列出目录中的文件和子目录 files = os.listdir(abs_path) file_list = ''.join(f'<li><a href="/{path}/{file}">{file}</a></li>' for file in files) parent_dir = os.path.dirname(path) if parent_dir == '': parent_dir = '/' self.wfile.write(f""" <html> <head> <meta charset="utf-8"> </head> <body> <h1>文件上传与下载</h1> <form action="/upload{path}" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="上传"> </form> <br> <h2>可用文件和目录:</h2> <ul> <li><a href="{parent_dir}">.. (上级目录)</a></li> {file_list} </ul> </body> </html> """.encode('utf-8')) elif os.path.isfile(abs_path): # 处理文件下载请求 self.send_response(200) self.send_header('Content-type', 'application/octet-stream') self.send_header('Content-Disposition', f'attachment; filename={os.path.basename(abs_path)}') self.end_headers() with open(abs_path, 'rb') as f: self.wfile.write(f.read()) else: self.send_response(404) self.send_header('Content-type', 'text/html; charset=utf-8') self.end_headers() self.wfile.write('文件或目录未找到'.encode('utf-8')) def do_POST(self): """处理 POST 请求,处理文件上传""" path = urllib.parse.unquote(self.path) if path.startswith('/upload'): sub_path = path[len('/upload'):] abs_path = os.path.join(UPLOAD_DIR, sub_path.strip('/')) if not os.path.exists(abs_path): os.makedirs(abs_path, exist_ok=True) ctype, pdict = cgi.parse_header(self.headers['Content-Type']) if ctype == 'multipart/form-data': form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD': 'POST'}) file_item = form['file'] if file_item.filename: filename = file_item.filename filepath = os.path.join(abs_path, filename) with open(filepath, 'wb') as f: f.write(file_item.file.read()) self.send_response(200) self.send_header('Content-type', 'text/html; charset=utf-8') self.end_headers() self.wfile.write('文件上传成功'.encode('utf-8')) else: self.send_response(400) self.send_header('Content-type', 'text/html; charset=utf-8') self.end_headers() self.wfile.write('未上传文件'.encode('utf-8')) else: self.send_response(400) self.send_header('Content-type', 'text/html; charset=utf-8') self.end_headers() self.wfile.write('请求无效'.encode('utf-8')) else: self.send_response(404) self.send_header('Content-type', 'text/html; charset=utf-8') self.end_headers() self.wfile.write('请求无效'.encode('utf-8')) def run(server_class=HTTPServer, handler_class=RequestHandler, port=8000): server_address = ('', port) httpd = server_class(server_address, handler_class) print(f'正在启动服务器,端口 {port}...') httpd.serve_forever() if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='运行一个简单的 HTTP 服务器,支持文件上传和下载。') parser.add_argument('--port', '-p', default=8000, type=int, help='指定端口 [默认: 8000]') args = parser.parse_args() run(port=args.port)
Powered by ddoss.cn 12.0
©2015 - 2024 ddoss
渝公网安备50011302222260号 渝ICP备2024035333号 【实验平台安全承诺书】 小绿叶技术社区,优化网络中,点击查看配置信息
您的IP:192.168.122.82,2024-10-10 18:19:12,Processed in 0.04303 second(s).