1

I am trying to implement a simple HTTP server with a form enabling the user to upload a file.

I have got three code files: - A python script creating the webserver with BaseHTTPServer and CGIHTTPServer - A html file with my form - Another python script linked to that form

Web server:

#!/usr/bin/env python
# coding: utf-8


import BaseHTTPServer
import CGIHTTPServer

import cgitb; cgitb.enable() # enable CGI error reporting

PORT = 8000
server_address = ('', PORT)

server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler 
handler.cgi_directories = ['cgi-bin']


httpd = server(server_address, handler)

httpd.serve_forever()

index.html:

<html>
<body>
  <form enctype="multipart/form-data"
        action="save_file.py" method="POST">
    <p>File: <input type="file" name="filename"/></p>
    <p><input type="submit" value="Send"/></p>
  </form>
</body>
</html>

save_file.py (inside cgi-bin folder):

#!/usr/bin/env python
# coding: utf-8

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

form = cgi.FieldStorage()

# Get filename
fileitem = form['filename']

# Test if file uploaded
if fileitem.filename:
    message = 'ok'   
else:
    message = 'No file was uploaded'


print "Content-type: text/html"
print ""
print """
<html>
<body>
  <p> %s </p
</body>
</html>
""" % message

I can run the server, but when I click on Send to submit, after (or not) having selected a file, I have the following error message:

Error response

Error code 501.

Message: Can only POST to CGI scripts.

Error code explanation: 501 = Server does not support this operation.

4
  • 1
    Have you set the execute bit on your CGI script file? Commented Mar 6, 2017 at 16:12
  • See the example at pointlessprogramming.wordpress.com/2011/02/13/… for another example, which makes a pont of setting the execute bit Commented Mar 6, 2017 at 16:31
  • Yes I did set the execute bit on the cgi script. The link you provided is one example I read before coding this little server Commented Mar 6, 2017 at 17:06
  • try to move the save_file.py script outside your cgi-bin directory Commented Apr 23, 2017 at 16:03

0

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.