Java – uploading an image to the server will damage the image
There is an image upload method in my application, which needs to send images and strings to the server
The problem is that the server received content (images and strings), but when the image was saved on disk, it was corrupted and could not be opened
This is the relevant part of the script
HttpPost httpPost = new HttpPost(url);
Bitmap bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
String byteStr = new String(byteArray);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("--"+boundary+"\r\n");
stringBuilder.append("Content-Disposition: form-data; name=\"content\"\r\n\r\n");
stringBuilder.append(message+"\r\n");
stringBuilder.append("--"+boundary+"\r\n");
stringBuilder.append("Content-Disposition: form-data; name=\"image\"; filename=\"image.jpg\"\r\n");
stringBuilder.append("Content-Type: image/jpeg\r\n\r\n");
stringBuilder.append(byteStr);
stringBuilder.append("\r\n");
stringBuilder.append("--"+boundary+"--\r\n");
StringEntity entity = new StringEntity(stringBuilder.toString());
httpPost.setEntity(entity);
I can't change the server because other clients will use it and it works for them. I just need to know why the image is corrupted
resolvent:
When you execute a new string (bytearray), it converts the binary file into the default character set (usually UTF-8). Most character sets are not suitable for binary data. In other words, if you want to encode some binary strings into UTF-8 and then decode them back to binary, you will not get the same binary string
Since you use multipart coding, you need to write the entity stream directly. Apache HTTP client is helpful. See this guide or this Android guide for segmented upload
If you only need to use strings, you can safely convert a byte array to a string using the following command
String byteStr = android.util.Base64.encode(byteArray, android.util.Base64.DEFAULT);
However, please note that your server will need Base64 to decode the string back to the byte array and then save it to the image. In addition, because Base64 encoding is not as space efficient as the original binary file, the transmission size will be larger