How to use Python / CGI to upload files

I am trying to create a file download page that will ask the user for a file and will load when progress is displayed.

At the moment, I managed to create a simple HTML page that might call my python script. Then the python script will receive the file and load it at 1000 bytes.

I have two main problems (mainly because of a completely new one in this):

1) I can’t get the file size for calculating the percentage 2) I don’t know how to communicate between python on the server side and what is on the page to update the progress status, presumably javascript.

Will I change everything? Or is there a solution to my problems?

Here is my Python code:

#!/usr/local/bin/python2.5 import cgi, os import cgitb; cgitb.enable() try: import msvcrt msvcrt.setmode (0, os.O_BINARY) msvcrt.setmode (1, os.O_BINARY) except ImportError: pass form = cgi.FieldStorage() upload = form['file'] if upload.filename: name = os.path.basename(upload.filename) out = open('/home/oetzi/webapps/py/' + name, 'wb', 1000) message = "The file '" + name + "' was uploaded successfully" while True: packet = upload.file.read(1000) if not packet: break out.write(packet) out.close() else: message = "Derp... could you try that again please?" print """\ Content-Type: text/html\n <html><body> <p>%s</p> </body></html> """ % (message,) 
+6
javascript python html cgi
source share
1 answer

This is more complicated than it sounds, given how file uploads work in the HTTP protocol. Most web servers will run the CGI script only when the downloaded file is fully migrated, so there is no way to give feedback.

There are some Python libraries that are trying to solve this problem. For example: gp.fileupload (works with WSGI, not CGI).

The trick is to provide a way to request downloads through AJAX while maintaining the downloaded file. This is useless if the web server (e.g. Apache or nginx) is not configured to support the download progress function, because you are likely to see a jump from 0% to 100% in the progress bar.

I suggest you try Plupload , which works on the client side and is much simpler.

+6
source share

All Articles