Skip to content

Instantly share code, notes, and snippets.

@rymate1234
Created April 9, 2014 13:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rymate1234/10269992 to your computer and use it in GitHub Desktop.
Save rymate1234/10269992 to your computer and use it in GitHub Desktop.
function uploadFile(file) {
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e) {
$( ".progress" ).show();
var percentComplete = Math.ceil((e.loaded / e.total) * 100);
$("#info_text").text("Uploaded: " + percentComplete + "%");
$('.bar').width(percentComplete + "%");
console.log("Uploaded: " + percentComplete + "%");
};
xhr.onload = function() {
if (xhr.status == 200) {
console.log(xhr.response);
hostAddress = top.location.host.toString();
url = "http://" + hostAddress + xhr.response;
window.location = url;
} else if (xhr.status == 413) {
alert("The image is too large! It must be 25MB or less.");
} else {
alert("Something went wrong whilst uploading. This is probably a bug, so it'll be fixed soon!");
}
};
xhr.onerror = function() {
alert("Error! Upload failed. Can not connect to server.");
};
xhr.open("POST", "/upload", true);
xhr.setRequestHeader("Content-Type", file.type);
xhr.send(file);
}
@app.route('/upload', methods=['POST'])
def upload():
if request.method == 'POST':
file = request.data
image_type = imghdr.what(file)
print "test"
if file:
file_id = id_generator()
file_ext = "png"
print "test"
filename = file_id + "." + file_ext
db = get_db()
print "test"
db.execute('insert into entries (file_name, title, file_ext) values (?, ?, ?)',
[file_id, "", file_ext])
print "test"
db.commit()
image = open(os.path.join(app.config['UPLOAD_FOLDER'], filename), 'w+')
image.write(request.data)
image.close()
print "Uploaded as " + os.path.join(app.config['UPLOAD_FOLDER'], filename)
return "/view/" + file_id
else:
return "NO FILE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment