[Django] [channels] [python]如何上传静态文件(图像,文档)?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Django] [channels] [python]如何上传静态文件(图像,文档)?相关的知识,希望对你有一定的参考价值。

我刚刚完成了频道教程,并花了将近一周的时间编写用于上传静态文件的代码。您能帮我写js和Consumer.py吗?预先谢谢你。

我特别不明白:1.如何编写js将静态数据发送到consumer.py2.如何从js的Consumer.py中获取静态数据。

我的代码是:

js
<script>

   var obj = document.getElementById('talk_element');
            obj.scrollTop = obj.scrollHeight;

    var roomName =  room.pk ;

    var chatSocket = new WebSocket(
        'ws://' + window.location.host +
        '/ws/room/' + roomName + '/');

    chatSocket.onmessage = function(e) 
        var data = JSON.parse(e.data);
        var message = data['message'];
        var file = data['file'];
        var created_by = data['created_by']

        var user = ` user `;

        if (created_by == user) 
            document.getElementById('talk_element').innerhtml += `
            <li class="container card-text text-right text-black">
                <span class="speech-bubble-user text-left">$message</span>
                <img src="$file" max-width="350" height=auto/>
             </li>`;
         else 
            document.getElementById('talk_element').innerHTML += `
            <li class="container card-text text-left text-black">
                <span class="container speech-bubble text-left">$message</span>
             </li>`;
            
    ;

    chatSocket.onclose = function(e) 
        console.error('Chat socket closed unexpectedly');
    ;

    document.querySelector('#chat-message-input').focus();
    document.querySelector('#chat-message-input').onkeyup = function(e) 
        if (e.keyCode === 13 && e.shiftKey)   // enter, return
            document.querySelector('#chat-message-submit').click();
        
    ;

    document.querySelector('#chat-message-submit').onclick = function(e) 
        var messageInputDom = document.querySelector('#chat-message-input');
        var message = messageInputDom.value;
        var userInputDom = document.querySelector('#creat_by');
        var user = userInputDom.value;
        var fileInputDom = document.querySelector('#document');
        var file = fileInputDom.value;

        chatSocket.send(JSON.stringify(
            'message': message,
            'created_by':user,
        ), file );

        messageInputDom.value = '';
    ;




</script>

consumer.py

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_pk']
        self.room_group_name = 'chat_%s' % self.room_name

        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

        self.accept()

    def disconnect(self, close_code):
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )

    # Receive message from WebSocket
    def receive(self, text_data=None):
        self.user = self.scope["user"]
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        created_by = text_data_json['created_by']
        file = text_data_json['created_by']
        room = Room.objects.get(pk=self.room_name)
        talk = Talk.objects.create(
            room=room,
            message=message,
            created_by=self.user,
            date=timezone.now
        )



        # Send message to room group

        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            
                'type': 'chat_message',
                'message': message,
                'created_by':created_by
            
        )

    # Receive message from room group
    def chat_message(self, event):
        message = event['message'] 
        created_by = event['created_by']

        # Send message to WebSocket
        self.send(text_data=json.dumps(
            'message': message,
            'created_by':created_by
        ))

答案

你明白了吗?您可以分享答案吗?

谢谢!

以上是关于[Django] [channels] [python]如何上传静态文件(图像,文档)?的主要内容,如果未能解决你的问题,请参考以下文章

Django使用Channels实现WebSocket--下篇

Django channel 简要解析

Django Channels 测试失败

Django 通道 websocket 连接和断开连接(Nginx + Daphne + Django + Channels)

Django Channels 2.0 channel_layers 不通信

Django-channels:AttributeError:'str'对象没有属性'profile'