Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File upload using Python with cgi

I'm trying to work file upload example in this website https://www.tutorialspoint.com/python/python_cgi_programming.htm

I have written a .py file. When i run this code, following error is occurs;

Traceback (most recent call last):
  File "C:/xampp/cgi-bin/file_upload.py", line 9, in <module>
    fileitem = form['filename']
  File "C:\Python3\lib\cgi.py", line 604, in __getitem__
    raise KeyError(key)
KeyError: 'filename'

And my .py file is below:

#!C:/Python3/python.exe

import cgi, os
import cgitb; cgitb.enable()

form = cgi.FieldStorage()

# Get filename here.
fileitem = form['filename']

# 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)
   open('F:/gelen/' + fn, 'wb').write(fileitem.file.read())

   message = 'The file "' + fn + '" was uploaded successfully'

else:
   message = 'No file was uploaded'

print ("""\
Content-Type: text/html\n
<html>
<body>
    <form enctype="multipart/form-data" 
                     action="/cgi-bin/file_upload.py" method="post">
   <p>File: <input type="file" name="filename" /></p>
   <p><input type="submit" value="Upload" /></p>
   </form>
   <p>%s</p>
</body>
</html>
""" % (message,))

How Can i solve this problem and why program doesn't see filename i don't understand

like image 479
Ahmet Gökhan Poyraz Avatar asked Sep 19 '25 18:09

Ahmet Gökhan Poyraz


1 Answers

Perhaps it is late for the person who asked, but I came across a similar problem. The following is what worked for me. As your error message shows the problem is coming from the line. fileitem = form['filename'] We can run the file in the browser as http://localhost:xxxx/file_upload.py What you'll see is the 'browse' button and the 'upload' button. Unless you browse and load some file the 'form' object won't be populated. It wouldn't contain the key 'filename', yet. We get the keyerror. So we need to put it inside an if statement. I also found some formatting error with the html part of the code. I slightly edited the code which is pasted below, runs well on Linux.

#!/usr/bin/python3
import cgi, sys, os
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
print('Content-type: text/html')
sys.path.insert(0, os.getcwd())

message = None

# Test if the file is loaded for the upload
if 'filename' in form:
    fileitem = form['filename']
    fn = os.path.basename(fileitem.filename)
    open('/home/jk/' + fn, 'wb').write(fileitem.file.read())
    message = 'The file "' + fn + '" was uploaded successfully'
else:
    message = 'No file was uploaded'

replyhtml = """
<html>
<body>
<form enctype="multipart/form-data" action="/cgi-bin/file_upload.py" method="post">
<p>File: <input type="file" name="filename" /></p>
<p><input type="submit" value="Upload" name=action/></p>
</form>
<p>%s</p>
</body>
</html>
"""
print(replyhtml % message)

I believe you have your server running in the current working directory. And the .py file need to be in the cgi-bin folder. A simple http server script:

import os
from http.server import HTTPServer, CGIHTTPRequestHandler

servaddr = ("localhost", 8888)
#http.server.SimpleHTTPRequestHandler(request, client_address, server)
server = HTTPServer(servaddr, CGIHTTPRequestHandler)
server.serve_forever()

References:

  1. Programming Python, Mark Lutz, 4th edition, Chapter1
  2. https://www.youtube.com/watch?v=oQ9FwkhUN1s
  3. http://cgi.tutorial.codepoint.net/file-upload
like image 84
jitheshKuyyalil Avatar answered Sep 21 '25 10:09

jitheshKuyyalil