Instantly share code, notes, and snippets.

Embed
What would you like to do?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>html page</title>
</head>
<body>
<form>
userfile: <input type="file" /> <br />
<progress max="100" value="0"></progress> <br />
<button type="submit">Submit</button>
</form>
<script>
document.cookie = 'ticket=123;domain=.example.com'
document.querySelector('form').addEventListener('submit', function(event) {
var xhr = new XMLHttpRequest();
var formdata = new FormData();
xhr.upload.onprogress = function (event) {
if (event.lengthComputable) {
console.info(Math.floor(event.loaded / event.total * 100));
document.querySelector('progress').value = Math.floor(event.loaded / event.total * 100)
}
}
xhr.open('POST', 'http://upload.example.com:8000', true);
xhr.withCredentials = true;
xhr.onload = function() {
alert(this.response);
}
formdata.append('username', 'dexter');
formdata.append('userfile',
document.querySelector('input[type=file]').files[0])
xhr.send(formdata);
event.preventDefault();
event.stopPropagation();
}, false);
</script>
</body>
</html>
# coding=utf-8
from wsgiref.simple_server import make_server
import cgi
import cgitb
import codecs
import logging
logging.basicConfig(filename='log.txt', filemode='w',
level=logging.DEBUG, format='%(message)s')
cgitb.enable()
def example(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
with codecs.open('index.html', 'r') as f:
for line in f:
yield line
def uploadExample(environ, start_response):
request_method = environ.get('REQUEST_METHOD')
if request_method == 'OPTIONS':
header = [('Access-Control-Allow-Origin', 'http://example.com:8000'),
('Access-Control-Allow-Methods', 'GET, POST, PUT'),
('Access-Control-Allow-Headers', 'origin, custom-header, content-type'),
('Access-Control-Allow-Credentials', 'true'),
('Access-Control-Allow-Max-Age', '60')]
start_response('200 OK', header)
return ''
elif request_method == 'POST':
header = [('Content-Type', 'text/plain'),
('Access-Control-Allow-Origin', 'http://example.com:8000'),
('Access-Control-Allow-Credentials', 'true')]
cookie = environ.get('HTTP_COOKIE')
start_response('200 OK', header)
if cookie and cookie.find('ticket=123') > -1:
fs = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ)
userfile = fs['userfile']
if userfile.filename:
return userfile.filename + ' upload complete!'
else:
return 'could\'t find the file'
else:
return 'cookie error'
else:
start_response('200 OK', [('Content-Type', 'text/plain')])
return repr(environ)
def application(environ, start_response):
return (example(environ, start_response)
if environ.get('HTTP_HOST') == 'example.com:8000'
else uploadExample(environ, start_response))
httpd = make_server('', 8000, application)
httpd.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment