简体   繁体   中英

How to send image file(binary data) using socket.io?

I have trouble to sending data from Android Client to NodeJS Server .

I use Socket.IO-client java library in my client.

But, there is not much information for me.

How can i sending binary data from android client to nodejs server?

You can use Base64 to encode the image:

   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;

    }

So basically you are sending a string to node.js

If you want to receive the image just decode in Base64:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM