Can one upload files using Python SimpleHTTPServer or cgi?

24.6k views Asked by At

I would like to have a simple web page on which user can upload files. What would be the simplest way to do it.

I know how to start SimpleHTTPServer but I do not know how I can upload files using SimpleHTTPServer. I do not even know if it is possible.

I found some code for uploading files using cgi but if I execute this code in the command line it just prints me HTML code on the screen.

2

There are 2 answers

2
textshell On

Yes, SimpleHTTPServer can receive http uploads with the correct request handler.

Basicly you need to define a do_POST method where a form or something similar uploads the data. the upload is then readble from self.rfile.

class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
     # ...
     def do_POST(self):
         for line in self.rfile:
             # do something with the line
             print line

of course if you want to upload from a browser you need to have a form somewhere that posts to the http server:

<form enctype="multipart/form-data" method="post" action="http://hostname.of.server:8080/">
  <input name="file" type="file"/>
  <input type="submit" value="upload"/>
</form>

More details in particular how to parse the raw data from the form-data can be found in the links posted as comments to the question.

0
C MaCleif On

I am still new to Python and have tried using the same code you added to your post. The only problem with it is that it only allows for single file upload. I wanted to upload multiple files at a time.

Using the still available code found here, you can replace the deal_post_data method with the following:

    form = cgi.FieldStorage(
    fp=self.rfile,
    headers=self.headers,
    environ={'REQUEST_METHOD':'POST'})

    self.send_response(200)
    self.end_headers()
    
    saved_fns = ""
    
    try:
        if isinstance(form['file'], list):
            for f in form['file']:
                print f.filename
                saved_fns = saved_fns + ", " + f.filename
                self.save_file(f)
                self.wfile.write(f.value)
        else:
            f = form['file']
            self.save_file(f)
            saved_fns = saved_fns + f.filename
            self.wfile.write(f.value)
        return (True, "File(s) '%s' upload success!" % saved_fns)
    except IOError:
        return (False, "Can't create file to write, do you have permission to write?")

Then add the following function to save the uploaded file:

def save_file(self, file):
    outpath = os.path.join("", file.filename)
    with open(outpath, 'wb') as fout:
        shutil.copyfileobj(file.file, fout, 100000)

Finally, change the html form to allow for multiple files to be uploaded at a time using the multiple tag in the inserted HTML.

I just finished testing this and it works fine.

Hope it is helpful