1
+ from http .server import BaseHTTPRequestHandler , HTTPServer
2
+ import os
3
+ import shutil
4
+ import cgi
5
+
6
+ # Define the port for your server
7
+ PORT = 8000
8
+
9
+ # Define the directory where uploaded files will be stored
10
+ UPLOAD_DIR = "uploads"
11
+
12
+ class RequestHandler (BaseHTTPRequestHandler ):
13
+ def do_GET (self ):
14
+ if self .path == '/' :
15
+ self .send_response (200 )
16
+ self .send_header ('Content-type' , 'text/html' )
17
+ self .end_headers ()
18
+ with open ("index.html" , "rb" ) as f :
19
+ self .wfile .write (f .read ())
20
+ else :
21
+ self .send_error (404 , "File not found" )
22
+
23
+ def do_POST (self ):
24
+ form = cgi .FieldStorage (
25
+ fp = self .rfile ,
26
+ headers = self .headers ,
27
+ environ = {'REQUEST_METHOD' :'POST' }
28
+ )
29
+
30
+ # Create the uploads directory if it doesn't exist
31
+ if not os .path .exists (UPLOAD_DIR ):
32
+ os .makedirs (UPLOAD_DIR )
33
+
34
+ # Save each uploaded file
35
+ for field in form .keys ():
36
+ field_item = form [field ]
37
+ if isinstance (field_item , list ):
38
+ # Handle multiple files with the same field name
39
+ for item in field_item :
40
+ if item .filename :
41
+ file_path = os .path .join (UPLOAD_DIR , os .path .basename (item .filename ))
42
+ with open (file_path , "wb" ) as f :
43
+ # Write file data in chunks to handle large files
44
+ shutil .copyfileobj (item .file , f , length = 131072 ) # Adjust chunk size as needed
45
+ else :
46
+ # Handle single file upload
47
+ if field_item .filename :
48
+ file_path = os .path .join (UPLOAD_DIR , os .path .basename (field_item .filename ))
49
+ with open (file_path , "wb" ) as f :
50
+ # Write file data in chunks to handle large files
51
+ shutil .copyfileobj (field_item .file , f , length = 131072 ) # Adjust chunk size as needed
52
+
53
+ # Send response
54
+ self .send_response (200 )
55
+ self .end_headers ()
56
+ self .wfile .write (b"All files uploaded successfully" )
57
+
58
+ def run ():
59
+ server_address = ('' , PORT )
60
+ httpd = HTTPServer (server_address , RequestHandler )
61
+ print (f"Server running on port { PORT } " )
62
+ httpd .serve_forever ()
63
+
64
+ if __name__ == '__main__' :
65
+ run ()
0 commit comments