问题描述:Android图像以base64格式上传到php服务器不起作用。
解决方法示例:
public String imageToBase64(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
return Base64.encodeToString(imageBytes, Base64.DEFAULT);
}
public void uploadImage(String base64Image) {
String url = "http://example.com/upload.php";
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image", base64Image)
.build();
Request request = new Request.Builder()
.url(url)
.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 {
// 处理上传成功的情况
}
});
}
请注意,在实际使用中,您可能需要更多的错误处理和数据验证。此示例仅提供基本的解决方案。