Skip to content

Instantly share code, notes, and snippets.

@an0ndev
Created November 1, 2020 00:43
Show Gist options
  • Select an option

  • Save an0ndev/eb62382135511b296b5299cc4eb4decd to your computer and use it in GitHub Desktop.

Select an option

Save an0ndev/eb62382135511b296b5299cc4eb4decd to your computer and use it in GitHub Desktop.
Simple Flask-based file upload page
import flask, werkzeug.utils, os, os.path
UPLOADS_DIR = "uploads"
if not os.path.exists (UPLOADS_DIR): os.mkdir (UPLOADS_DIR)
app = flask.Flask (__name__)
@app.route ("/")
def root ():
return """
<style>
/* You know I had to do it to 'em */
:root {
--black: #000000;
--green: #00FF00;
}
html {
height: 100%;
display: flex; align-items: center; justify-content: center;
}
body {
height: 100%; margin: 0px;
display: flex; flex-direction: column; align-items: center; justify-content: center;
}
body > * {
margin: 10px;
}
html, body, input, button, p, small {
background: var(--black);
}
button {
border: 1px solid var(--green);
}
input, button, p, small {
color: var(--green);
font-family: monospace;
}
</style>
<input type="file" name="file">
<small>(Blame whoever wrote the spec for the file chooser not me)</small>
<button>Submit</button>
<p>Not started</p>
<script>
/* shitty code by eric reed 10-31-20. complaints go to 4403840834 */
window.onerror = () => alert ("Shit went down, check console");
var $ = selector => document.querySelector (selector);
var ready = true;
$ ("button").onclick = event => {
if (!ready) return;
if ($ ("input").files.length !== 1) return;
var formData = new FormData ();
formData.append ("file", $ ("input").files [0]);
var xhr = new XMLHttpRequest ();
xhr.upload.onprogress = event => {
$ ("p").innerText = `${event.loaded} / ${event.total} (${(event.loaded / event.total) * 100}%)`;
};
xhr.onreadystatechange = event => {
if (xhr.readyState == XMLHttpRequest.DONE) {
$ ("p").innerText = "Done";
ready = true;
}
};
xhr.open ("POST", "/upload", true);
xhr.send (formData);
ready = false;
};
</script>
"""
@app.route ("/upload", methods = ["POST"])
def upload ():
_file = flask.request.files ["file"]
_file.save (UPLOADS_DIR + os.path.sep + werkzeug.utils.secure_filename (_file.filename))
return flask.redirect ("/")
if __name__ == "__main__":
app.run ("0.0.0.0", 42069, ssl_context = ("cert.pem", "key.pem"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment