Javascript 想在android中使用node.js和socket.io发送图像吗
我正在两个用户之间创建聊天应用程序,现在我可以使用node.js和socket.io与不同的用户进行简单的文本聊天。现在问题出现在这里,因为我必须在聊天应用程序中发送图像,在搜索了一整天之后,我无法获得完美的node.js,在其中我可以在聊天应用程序中发送图像。所以我想知道是否可以使用node.js发送图像。下面是我的simple node.js文件,用于从一个用户向另一个用户发送简单的文本消息Javascript 想在android中使用node.js和socket.io发送图像吗,javascript,android,node.js,sockets,Javascript,Android,Node.js,Sockets,我正在两个用户之间创建聊天应用程序,现在我可以使用node.js和socket.io与不同的用户进行简单的文本聊天。现在问题出现在这里,因为我必须在聊天应用程序中发送图像,在搜索了一整天之后,我无法获得完美的node.js,在其中我可以在聊天应用程序中发送图像。所以我想知道是否可以使用node.js发送图像。下面是我的simple node.js文件,用于从一个用户向另一个用户发送简单的文本消息 socket.on('privateMessage', function(data) { s
socket.on('privateMessage', function(data) {
socket.get('name', function (err, name) {
if(!err) {
// get the user from list by its name to get its socket,
// then emit event privateMessage
// again here we want to make you clear
// that every single client connection has its own
// unique SOcket Object, we need to get this Socket object
// to communicate with every other client. The socket variable
// in this scope is the client who wants to send the private
// message but the socket of the receiver is not know.
// Get it from the saved list when connectMe handlers gets called
// by each user.
onLine[data.to].emit('newPrivateMessage',{from:name, msg:data.msg, type:'Private Msg'})
}
});
});
我能想到的最简单的方法就是对图像进行编码并通过文本管道发送。您需要使用标题信息区分文本和图像消息(可能发送JSON对象?) 您可以使用Base64版本的图像并按如下方式发送:
onLine[data.to].emit('newPrivateMessage',{from:name, img:data.img.toString('base64'), type:'Private Msg'})
。。然后在客户端接收并创建一个映像
socket.on("newPrivateMessage", function(data) {
if (data.img) {
var img = new Image();
img.src = 'data:image/jpeg;base64,' + data.img;
// Do whatever you want with your image.
}
});
更新
下面是我在下面评论的链接中的一个片段。如您所见,它从输入中获取图像,读取它并发送到服务器。之后,您可以将相同的数据从服务器发送到另一个客户端
有关完整示例,请阅读
JavaScript(客户端)
HTML
上面的代码片段显示了如何读取文件并将数据编码为base64
字符串。然后你可以像字符串一样发送它(我假设)
以下是完整的示例:
我还发现了Base64.Encoder
(java.util
包)的功能,您可以使用它。实际上如何从一个用户发送到另一个用户。您给出的示例是将图像从node.js发送给用户,我想使用node.js将图像从用户发送给另一个用户。您能告诉我如何将图像发送到node.js服务器吗?请看下面的代码:您能告诉我如何将图像从json发送到node.js服务器吗?您所说的从json发送到node.js服务器的是什么意思?
...
$('#imageFile').on('change', function(e) {
var file = e.originalEvent.target.files[0],
reader = new FileReader();
reader.onload = function(evt) {
var jsonObject = {
'imageData': evt.target.result
}
// send a custom socket message to server
socket.emit('user image', jsonObject);
};
reader.readAsDataURL(file);
});
...
...
Image file: <input type="file" id="imageFile" /><br/>
...
File file = new File("path/to/the/image");
try {
FileInputStream imageInFile = new FileInputStream(file);
byte imageData[] = new byte[(int) file.length()];
imageInFile.read(imageData);
// Converting Image byte array into Base64 String
String imageDataString = Base64.encodeBase64URLSafeString(imageData);
} catch (...) {
...
}