ich versuche ein einfaches CGI Script zum Laufen zu bekommen, das einen Dateiupload handelt. Solange die Datei nix binäres ist, klappt das auch wunderbar. Wenn doch bekomme ich einen UnicodeDecodeError - klar, da Python3.0 den Datenstrom als Unicode behandelt.
Das ist das Script:
Code: Alles auswählen
#!/usr/bin/python3.0
import cgi, os
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
# Generator to buffer file chunks
def fbuffer(f, chunk_size=10000):
while True:
chunk = f.read(chunk_size)
if not chunk: break
yield chunk
# A nested FieldStorage instance holds the file
fileitem = form['file']
# Test if the file was uploaded
if fileitem.filename:
# strip leading path from file name to avoid directory traversal attacks
fn = os.path.basename(fileitem.filename)
with open('/tmp/' + fn, 'wb', 10000) as f:
# Read the file in chunks
for chunk in fbuffer(fileitem.file):
f.write(chunk)
print('Content-Type: text/html')
print()
print("""
<html>
<body>
<p>{0} erforglreich hochgeladen!</p>
</body>
</html>
""".format(fileitem.filename))
Nun meine Frage: Wie teile ich dem Interpreter mit, dass das was da kommt binär ist, und einfach bit für bit in eine Datei geschrieben werden soll? Wie würdet ihr dieses Problem lösen (und habt ihr Beispielcode zur Hand)?
Noch ein Hinweis: Ich bin kein Programmierer, und das was ich hier mache ist nur ein kleiner Test. Um mich in WSGI und ein Framework einzuarbeiten fehlt mir im Moment die Zeit, und ist für diesen Zweck wohl auch ein wenig Overkill.
Danke im Voraus für eure Antworten!