42-webserv / SpaceX

Non-blocking I/O HTTP WEB Server
2 stars 1 forks source link

[🐞] HTTP Upload Form #51

Closed enaenen closed 1 year ago

enaenen commented 1 year ago

HTTP upload form body

codeyoma commented 1 year ago

multipart/form-dataλŠ” cgi둜 κ°€κ²Œλ” ν•˜λŠ”κ²Œ νŽΈν•  것 κ°™μ•„μš”.

python ν”„λ‘œκ·Έλž¨ μˆ˜μ •ν•΄μ„œ 잘 μ €μž₯λ˜λ„€μš”

#!/usr/bin/python
import cgi, os
import cgitb; cgitb.enable()
# import cgitb; cgitb.enable(display=0, logdir="./log")

print("Content-Type: text/html")
# Parse the form data
form = cgi.FieldStorage()
# Extract the uploaded files
files = {}
message = "file uploaded failed"
for field in form.keys():
    message = "file uploaded success"
    # Check if the field is a file field
    if isinstance(form[field], cgi.FieldStorage) and form[field].filename:
        # Save the file to the specified location
        with open("./tmp/" + form[field].filename, 'wb') as f:
            f.write(form[field].file.read())
        files[field] = form[field].filename

# Print the uploaded files
response = "<html><body><center>"
response += "<h1>{}<h1>".format(message)
for field, filename in files.items():
    response += "<p>{}: {}</p>\n".format(field, filename)
response += "</center></body></html>"

print("Content-Length: {}".format(len(response)))
print()
print(response)
enaenen commented 1 year ago

πŸ‘

codeyoma commented 1 year ago