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.

Baptiste
  • 25
  • 1
  • 10
  • 1
    Have you set the execute bit on your CGI script file? – holdenweb Mar 06 '17 at 16:12
  • See the example at https://pointlessprogramming.wordpress.com/2011/02/13/python-cgi-tutorial-1/ for another example, which makes a pont of setting the execute bit – holdenweb Mar 06 '17 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 – Baptiste Mar 06 '17 at 17:06
  • try to move the save_file.py script outside your cgi-bin directory – Liam Apr 23 '17 at 16:03

0 Answers0