Reputation: 135
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 {
}
});
}
Upvotes: 3
Views: 7576
Reputation: 459
You don't need to base64-encode the image data, just use byteArray
:
.addFormDataPart("image", "filename.jpg",
RequestBody.create(MediaType.parse("image/*jpg"), byteArray))
Upvotes: 4