Skip to content

Instantly share code, notes, and snippets.

@helambuapps
Last active August 29, 2015 14:12
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 helambuapps/5f47b538168355fdf4ba to your computer and use it in GitHub Desktop.
Save helambuapps/5f47b538168355fdf4ba to your computer and use it in GitHub Desktop.
File Upload from browser using WAMP (Web Apps Messaging Protocol)
Create a folder .crossbar and put the file ".config.yaml" inside it. Unfortunately Github doesn't let me create a folder :(
Run the crossbar router before running app.py and index.html
controller: {}
workers:
- realms:
- name: realm1
roles:
- name: anonymous
permissions:
- {call: true, publish: true, register: true, subscribe: true, uri: '*'}
transports:
- endpoint: {port: 8080, type: tcp}
paths:
/: {directory: .., type: static}
ws: {type: websocket}
type: web
type: router
from autobahn.asyncio.wamp import ApplicationSession
from autobahn import wamp
from asyncio import coroutine
import base64
class MyComponent(ApplicationSession):
@wamp.register("com.myapp.upload")
def upload(self, imagename, image):
imgdata = base64.b64decode(image)
with open(imagename, 'wb') as file:
file.write(imgdata)
@coroutine
def onJoin(self, details):
res = yield from self.register(self)
print("{} procedures registered.".format(len(res)))
if __name__ == '__main__':
from autobahn.asyncio.wamp import ApplicationRunner
runner = ApplicationRunner(url="ws://localhost:8080/ws", realm="realm1")
runner.run(MyComponent)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<input type="file" multiple="true" id="files" accept="image/*">
<script>AUTOBAHN_DEBUG = false;</script>
<script src="http://autobahn.s3.amazonaws.com/autobahnjs/latest/autobahn.min.jgz"></script>
<script>
var connection = new autobahn.Connection({
url: "ws://localhost:8080/ws",
realm: "realm1"
});
connection.onopen = function (session, details) {
function handleFileUpload(event) {
var files = event.target.files;
for(var i=0; i<files.length; ++i) {
var file = files[i];
// Ignore the non image types
if (!file.type.match('image.*')) {
continue;
}
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = (function(theFile) {
return function(event) {
var base64_str = event.target.result.split(";base64,")[1];
session.call("com.myapp.upload", [theFile.name, base64_str]);
};
})(file);
}
}
document.getElementById('files').addEventListener('change',
handleFileUpload, false);
};
connection.onclose = function (reason, details) {
console.log("Connection lost: " + reason);
};
connection.open();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment