I'm using OKhttp for network requests. Trying to upload an image to a server. This is the way I tried, but it's not working. What am I doing wrong?
client = new OkHttpClient.Builder()
.build();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("", "",
RequestBody.create(MediaType.parse("image/*"), encodedImage))
.build();
Request request = new Request.Builder()
.url(serverUrl)
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
}
You don't need to base64-encode the image data, just use byteArray:
.addFormDataPart("image", "filename.jpg",
RequestBody.create(MediaType.parse("image/*jpg"), byteArray))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With