Reputation: 32873
I am uploading in android. To do so I am following this tutorial. My current code gives me this error in my logcat
06-23 10:10:22.990: D/dalvikvm(25853): GC_EXTERNAL_ALLOC freed 48K, 50% free 2723K/5379K, external 0K/0K, paused 33ms
06-23 10:10:23.030: E/log_tag(25853): Error in http connection java.net.UnknownHostException: www.example.info
06-23 10:10:23.115: D/CLIPBOARD(25853): Hide Clipboard dialog at Starting input: finished by someone else... !
Here is how my code looks like
public class UploadFileActivity extends Activity {
/** Called when the activity is first created. */
Button bUpload;
EditText etParam;
InputStream is;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeToString(ba, 0);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",ba1));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.info/androidfileupload/index.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch(Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
}
Here is what I am using on the server side
<?php
$base=$_REQUEST['image'];
echo $base;
// base64 encoded utf-8 string
$binary=base64_decode($base);
// binary, utf-8 bytes
header('Content-Type: bitmap; charset=utf-8');
// print($binary);
//$theFile = base64_decode($image_data);
$file = fopen('test.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
echo '<img src=test.jpg>';
?>
Upvotes: 2
Views: 2917
Reputation: 2176
The UnknownHostException
is related to your url domain or there is no Internet/Network connectivity,
So make sure you have added Internet permission in your AndroidManifest file.
<uses-permission android:name="android.permission.INTERNET" />
Hope This Helps
Upvotes: 2
Reputation: 2612
I followed that same tutorial. Worked as long as the images were small enough.
Otherwise you can get an Out Of Memory issue at:
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
To answer you question -
Could you tell me how can I keep the name of the image as original name? I mean, I want to use that same name of the image at the time of uploading.
You can add a variable to the URL request that holds the original name. Otherwise you won't be able to embed it into the 64Byte encoded string.
Something like this:
"http://www.example.info/androidfileupload/index.php?name=filename"
PHP side looks like
$FileName = $_GET['name'];
Upvotes: 2