I would like to upload files and images using django-channels but i don't have any idea where to start. Seems like there is not much documentation about websockets and file/image uploads. Any ideas?
Django channels file/image upload
9.1k Views Asked by cwirz At
3
There are 3 best solutions below
1
On
I also faced the same problem and I solved it by uploading the the Image/File in S3 bucket. we just need to decode the base64 code and upload the file and return the URL to websocket. We can also provide preview of the image by providing the file type.
def file_upload(self, data):
# Convert decode the base64 data
file = base64.b64decode(data['data']['content'].split(',')[-1])
filename = data['data']['filename']
type = data['data']['type']
AWS_ACCESS_KEY_ID = getattr(settings, "AWS_S3_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = getattr(settings, "AWS_S3_SECRET_ACCESS_KEY")
bucket_name = getattr(settings, "AWS_STORAGE_BUCKET_NAME")
conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
bucket = conn.get_bucket(bucket_name)
k = Key(bucket)
k.key = getattr(settings, "AWS_CHAT_DIR") + '/' + filename
k.set_metadata('Content-Type', type)
k.set_contents_from_string(file)
url = 'https://' + getattr(settings, "AWS_BUCKET_URL") + '/' + k.key
message = url
content = {
'command': 'new_message',
'message': self.message_to_json(message)
}
return self.send_chat_message(content)
0
On
Easy Approach is to use FileReader. On Client Side you will have the following code.
//connect the websocket with server
var client = new WebSocket('ws://hostname')
//now get the base64 src for image for it i have
written a function.
function toDataURL(file, callback) {
var reader = new FileReader();
reader.onload = function () {
var dataURL = reader.result;
callback(dataURL);
}
reader.readAsDataURL(file);
}
document.getElementById('image').addEventListener('change', function(event){
var files = event.target
var file = files[0];
toDataURL(file, function(dataURL){
client.send(JSON.stringify({
'command':'new_file',
'dataURL': dataURL
}))
})
})
this will send the dataURL to your Consumer and then from there you can send it to the group i.e. to all users and can use this dataURL as src of image to show the image on browser:)
for example:
<img src=dataURL>
you can create this using javascript function for example you can use document.createElement('img') and provide the src as dataURL with javascript.
The only real way to do this is with Channels 2 because the consumers persist for the duration of the session and you can put a file object on it as an instance variable.
You can see how I use the file field and first send some initialization parameters on it. I pulled out the important parts:
In the consumer we check if it is text data and if it is we process it as JSON to set up the file. If its binary data we write each chunk out like this.