【问题标题】:How to send image file(binary data) using socket.io?如何使用 socket.io 发送图像文件(二进制数据)?
【发布时间】:2016-07-10 10:20:24
【问题描述】:

我无法将数据从Android Client 发送到NodeJS Server

我在客户端使用Socket.IO-client java 库。

但是,对我来说没有太多信息。

如何将二进制数据从 android 客户端发送到 nodejs 服务器?

【问题讨论】:

    标签: java android node.js file-upload socket.io


    【解决方案1】:

    您可以使用 Base64 对图像进行编码

       public void sendImage(String path)
        {
            JSONObject sendData = new JSONObject();
            try{
                sendData.put("image", encodeImage(path));
                socket.emit("message",sendData);
            }catch(JSONException e){
            }
        }
    
       private String encodeImage(String path)
        {
            File imagefile = new File(path);
            FileInputStream fis = null;
            try{
                fis = new FileInputStream(imagefile);
            }catch(FileNotFoundException e){
                e.printStackTrace();
            }
            Bitmap bm = BitmapFactory.decodeStream(fis);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
            byte[] b = baos.toByteArray();
            String encImage = Base64.encodeToString(b, Base64.DEFAULT);
            //Base64.de
            return encImage;
    
        }
    

    所以基本上你是在向 node.js 发送一个字符串

    如果您想接收图像,只需在 Base64 中解码

    private Bitmap decodeImage(String data)
    {
        byte[] b = Base64.decode(data,Base64.DEFAULT);
        Bitmap bmp = BitmapFactory.decodeByteArray(b,0,b.length);
        return bmp;
    }    
    

    【讨论】:

      猜你喜欢
      • 2016-03-07
      • 2016-09-16
      • 1970-01-01
      • 2017-10-31
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 2016-02-02
      • 2020-09-01
      相关资源
      最近更新 更多