Send image as json entry android

断了今生、忘了曾经 提交于 2019-12-03 09:09:52
Paresh Mayani

If you want to include Image in a JSON object which you will be sending in a request, convert Image into Base64 string and put this string into the JSON object.

For example:

String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);

Check:

Well, it's kind of experimental, but you can create an array of bytes out of the bitmap, and then create a new string with that array of bytes, and then send it to the server.

However, why don't you just send a POST request to save the image directly, without any experimental processing or parsing?

Try base64-encoding the image (like below, where the Uri is your Image - but beware: ImageView has no Getter for the ImageUri, so you have to store it by yourself!):

Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);

ContentResolver cr = getContentResolver();
InputStream is = cr.openInputStream(uri);

byte[] data = getBytesFromFile(is);

byte[] encoded_data = Base64.encodeBase64(data);
data_string = new String(encoded_data);

Now you have an base64-encoded String data_string that you can send with your JSON request. On the server-side you just have to decode the String and save the picture.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!