想要在android中使用node.js和socket.io发送图像

我正在两个用户之间创build一个聊天应用程序,现在我可以使用node.js和socket.io与不同的用户进行简单的文本交谈。 现在问题出现了,因为我必须在聊天应用程序中发送图像,并且在search整个漫长的一天之后,我无法获得完美的可以在聊天应用程序中发送图像的node.js。 所以我想知道是否有可能使用node.js发送图像。 这里是我简单的node.js文件,用于将简单的文本消息从一个用户发送到另一个用户。

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'}) } }); }); 

您可以使用图像的Base64版本,并像这样发送:

 onLine[data.to].emit('newPrivateMessage',{from:name, img:data.img.toString('base64'), type:'Private Msg'}) 

然后在客户端接收它并创build一个图像

 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. } }); 

UPDATE

以下是我在下面评论的链接中摘录的一段代码。 正如你可以看到它从input获取图像, read它并发送到服务器。 之后,您可以将相同的数据从服务器发送到另一个客户端。

对于完整的例子,请阅读文章 。

JavaScript(客户端)

 ... $('#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); }); ... 

HTML

 ... Image file: <input type="file" id="imageFile" /><br/> ... 

更新2

这是我发现的一个例子:

Java(客户端)

 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 (...) { ... } 

上面的代码展示了如何读取文件并将数据编码成base64string。 那么你可以发送它就像一个string(我假设)。

这里是完整的例子: 如何将图像转换为string和string到Java中的图像?

我也发现encodeToStringjava.util包)的encodeToString函数,您可以使用它。

我能想到的最简单的方法是简单地Base64编码图像并通过文本pipe道发送。 你需要区分文本和图像消息与头信息(也许发送一个JSON对象?)。