Django 频道文件/图片上传 [英] Django channels file/image upload

查看:15
本文介绍了Django 频道文件/图片上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 django-channels 上传文件和图像,但我没有想法从哪里开始.似乎没有太多关于 websockets 和文件/图像上传的文档.有什么想法吗?

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?

推荐答案

我也遇到了同样的问题,我通过上传 S3 存储桶中的图像/文件解决了这个问题.我们只需要解码base64代码并上传文件并将URL返回给websocket.我们还可以通过提供文件类型来提供图像的预览.

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)

这篇关于Django 频道文件/图片上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆