python3 simple webdav

84 阅读1分钟
#
import http.server
import socketserver
import cgi
import os

PORT = 8000
UPLOAD_FOLDER = 'uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

class CustomHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    def do_POST(self):
        if self.path == '/upload':
            form = cgi.FieldStorage(
                fp=self.rfile, 
                headers=self.headers,
                environ={'REQUEST_METHOD':'POST',
                        'CONTENT_TYPE':self.headers['Content-Type'],
                        })

            file_item = form['file']
            if file_item.filename:
                file_path = os.path.join(os.getcwd(), UPLOAD_FOLDER, file_item.filename)
                with open(file_path, "wb") as f:
                    f.write(file_item.file.read())
                message = "File '{}' upload successful!".format(file_item.filename)
            else:
                message = "No file was uploaded"

            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            response_html = f"<html><body><p>{message}</p><p><a href='/'>=> HomePage</a></p></body></html>"
            self.wfile.write(response_html.encode())
        else:
            self.send_response(404)
            self.end_headers()
            self.wfile.write(b'Not found.')

    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        content = '''
        <!doctype html>
        <title>Upload File</title>
        <h1>Upload File</h1>
        <form method="post" enctype="multipart/form-data" action="/upload">
          <input type="file" name="file">
          <input type="submit" value="Upload">
        </form>
        '''
        items = os.listdir(os.path.join(os.getcwd(), self.path.lstrip('/'))) 
        content += '<ul>'
        for item in items:
            content += '<li><a href="/{}">{}</a></li>'.format(item, item)
        content += '</ul>'
        content += "<p><a href='/'>=> HomePage</a></p>"
        self.wfile.write(content.encode())

with socketserver.TCPServer(("", PORT), CustomHTTPRequestHandler) as httpd:
    print(f"Serving on port {PORT}")
    httpd.serve_forever()