mateomtb
asked on
Python file upload progress bar with javascript
I have this basic file upload script working from a tutorial I found linked to from around here. I have it all working and am now trying to get a browser side progress bar working, the files being uploaded are 200MB+ and some sort of status is needed. From some reading around here my thoughts are that python should be able to deliver some sort of current status that I can send to a javascript function.
html
python (uploadtest.py)
Javascript example I found around here.
html
<html><body>
<form enctype="multipart/form-data" action="uploadtest.py" method="post">
<p>File: <input type="file" name="file"></p>
<p><input type="submit" value="Upload"></p>
</form>
</body></html>
python (uploadtest.py)
#!/usr/bin/python
import cgi, os
import cgitb; cgitb.enable()
try: # Windows needs stdio set for binary mode.
import msvcrt
msvcrt.setmode (0, os.O_BINARY) # stdin = 0
msvcrt.setmode (1, os.O_BINARY) # stdout = 1
except ImportError:
pass
form = cgi.FieldStorage()
# Generator to buffer file chunks
def fbuffer(f, chunk_size=10000):
while True:
chunk = f.read(chunk_size)
if not chunk: break
yield chunk
# A nested FieldStorage instance holds the file
fileitem = form['file']
# Test if the file was uploaded
if fileitem.filename:
# strip leading path from file name to avoid directory traversal attacks
fn = os.path.basename(fileitem.filename)
f = open('files/' + fn, 'wb', 10000)
# Read the file in chunks
for chunk in fbuffer(fileitem.file):
f.write(chunk)
f.close()
message = 'The file "' + fn + '" was uploaded successfully'
else:
message = 'No file was uploaded'
print """\
Content-Type: text/html\n
<html><body>
<p>%s</p>
</body></html>
""" % (message,)
Javascript example I found around here.
<div width="200px" height="30px" ><img height="30px" width="1px" id="loader" src="loader.jpg" /></div>
<script type="text/javascript">
function progress(percent)
{
document.getElementById('loader').width=Math.round(percent/200);
}
</script>
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER