Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django channels file/image upload

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?

like image 922
cwirz Avatar asked Jan 05 '17 18:01

cwirz


1 Answers

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)
like image 104
Lokesh Avatar answered Sep 30 '22 19:09

Lokesh