4

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

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

If the directory where the script is running is /path/to/dir then the /path/to/dir/files directory must exist. If it does not it will fail. and also to upload a file the HTML form must have the enctype attribute set to multipart/form-data.

Comments

0

Also if you are uploading images to an ec2 linux server then the folder you want to upload your files into must have the permissions drwxrwxrwt.

chmod 777 -R myfolder
chmod o+t -R myfolder

this worked for me

Referred from here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.