Reputation: 11
I am programming an app, which among other things an user can upload an avatar. It seems to work, but at the end the uploaded file/image is empty on server. I guess the image will not be decoded on serverside correctly. Following logcat message:
07-12 16:54:25.809: E/ViewRootImpl(13702): sendUserActionEvent() mView == null
07-12 16:54:26.176: E/JSON(13702): img_xebf47_2014-07-12-16-07-16.jpg
07-12 16:54:26.207: E/JSON Parser(13702): Error parsing data org.json.JSONException: Value img_xebf47_2014-07-12-16-07-16.jpg of type java.lang.String cannot be converted to JSONObject
On Android side I have folowing classes:
Relevant areas in UploadAvatarActivity.java:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case PICK_FROM_FILE:
/**
* After selecting image from files, save the selected path
*/
mImageCaptureUri = data.getData();
imagepath = getPath(mImageCaptureUri);
Bitmap bitmap2 = BitmapFactory.decodeFile(imagepath);
mImageView.setImageBitmap(bitmap2);
NetAsync();
break;
}
@Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
ByteArrayOutputStream bao = new ByteArrayOutputStream();
byte[] ba = bao.toByteArray();
int flag = 0;
String krt = Base64.encodeToString(ba, flag);
JSONObject json = userFunction.uploadAvatar(uid, krt);
return json;
}
UserFunctions.java:
public class UserFunctions {
private JSONParser jsonParser;
// URL of the PHP API
private static String upload_avatarURL = "http://xxxxxxxx/xxxAPI/";
// Tag for serverside
private static String upload_avatar_tag = "uploadavatar";
// constructor
public UserFunctions() {
jsonParser = new JSONParser();
}
/**
* Function to upload avatar
**/
public JSONObject uploadAvatar(String uid, String image) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", upload_avatar_tag));
params.add(new BasicNameValuePair("uid", uid));
params.add(new BasicNameValuePair("image", image));
JSONObject json = jsonParser.getJSONFromUrl(upload_avatarURL, params);
return json;
}
}
And here JASONParser which handles the HTTp-request:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
And finally on serverside I have followin PHP-code:
if ($tag == 'uploadavatar') {
$uid = $_POST['uid'];
$base = $_POST["image"];
if (isset($base)) {
$suffix = $db->createRandomID();
$image_name = "img_".$suffix."_".date("Y-m-d-H-m-s").".jpg";
// base64 encoded utf-8 string
$binary = base64_decode($base);
// binary, utf-8 bytes
header("Content-Type: bitmap; charset=utf-8");
$file = fopen("../images/post_images/" . $image_name, "wb");
fwrite($file, $binary);
fclose($file);
die($image_name);
} else {
die("No POST");
}
}
In case someone else has the same issue:
I fixed my problem with following change:
@Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
// Here I had to compress and encode to string!!
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap2.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String krt = Base64.encodeToString(imageBytes, Base64.DEFAULT);
JSONObject json = userFunction.uploadAvatar(uid, krt);
return json;
}
Upvotes: 0
Views: 976
Reputation: 11
In case someone else has the same issue:
I fixed my problem with following change:
@Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
// Here I had to compress and encode to string!!
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap2.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String krt = Base64.encodeToString(imageBytes, Base64.DEFAULT);
JSONObject json = userFunction.uploadAvatar(uid, krt);
return json;
}
Upvotes: 1