如何上传静态文件(图像、文档)?
Posted
技术标签:
【中文标题】如何上传静态文件(图像、文档)?【英文标题】:How is it possible to upload static files (image, documents)? 【发布时间】:2019-09-30 10:12:05 【问题描述】:刚看完频道教程,忙着写上传静态文件的代码快一周了。你能帮我写js和consumer.py吗?提前谢谢你。
我特别不明白:
-
如何编写js发送静态数据到consumer.py
如何从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- 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
))
【问题讨论】:
【参考方案1】:如果您希望 javascript 和 Python 都能正常通信,您需要运行 WebSocket server。例如,您可以使用Tornado 或this one 构建一个。
一旦你有了一个,你需要在client side做一些事情:
实例化一个 WebSocket 对象以建立连接
var exampleSocket = new WebSocket("wss://www.example.com/socketserver");
像这样向服务器发送数据(作为字符串、Blob 或 ArrayBudder)
exampleSocket.onopen = function (event)
exampleSocket.send("Here's some text that the server is urgently awaiting!");
;
如果你想传输对象,那么考虑使用 JSON
function sendText()
// Construct a msg object containing the data the server needs to process the message.
var msg =
type: "message",
text: document.getElementById("text").value,
id: clientID,
date: Date.now()
;
// Send the msg object as a JSON-formatted string.
exampleSocket.send(JSON.stringify(msg));
从服务器接收消息
exampleSocket.onmessage = function (event)
console.log(event.data);
如果您发送的是 JSON 对象,则解释消息的代码可能如下所示
exampleSocket.onmessage = function(event)
var f = document.getElementById("chatbox").contentDocument;
var text = "";
var msg = JSON.parse(event.data);
var time = new Date(msg.date);
var timeStr = time.toLocaleTimeString();
switch(msg.type)
case "id":
clientID = msg.id;
setUsername();
break;
case "username":
text = "<b>User <em>" + msg.name + "</em> signed in at " + timeStr + "</b><br>";
break;
case "message":
text = "(" + timeStr + ") <b>" + msg.name + "</b>: " + msg.text + "<br>";
break;
case "rejectusername":
text = "<b>Your username has been set to <em>" + msg.name + "</em> because the name you chose is in use.</b><br>"
break;
case "userlist":
var ul = "";
for (i=0; i < msg.users.length; i++)
ul += msg.users[i] + "<br>";
document.getElementById("userlistbox").innerHTML = ul;
break;
if (text.length)
f.write(text);
document.getElementById("chatbox").contentWindow.scrollByPages(1);
;
关闭连接
exampleSocket.close();
【讨论】:
以上是关于如何上传静态文件(图像、文档)?的主要内容,如果未能解决你的问题,请参考以下文章
Django - 将静态图像上传为默认 ImageField 文件