Can one upload files using Python SimpleHTTPServer or cgi?

Roman picture Roman · Dec 6, 2013 · Viewed 19.8k times · Source

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.

Answer

C MaCleif picture C MaCleif · Jun 1, 2016

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