我正在使用OKhttp进行网络请求。尝试将图像上传到服务器。这是我尝试的方式,但它不起作用。我做错了什么?
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 {
}
});
}
答案 0 :(得分:1)
您不需要对图像数据进行64位编码,只需使用byteArray
:
.addFormDataPart("image", "filename.jpg",
RequestBody.create(MediaType.parse("image/*jpg"), byteArray))