We are working on an application which has 2 modules.
Android Application.
PHP Application
PHP backend application runs on an Apache Server with Centos Server.
Android application basically clicks images, send to the server along with gps coordinates etc form information.
Now the problem arises when the image file is created on the server. When android app calls the url the '&' character is replaced by & amp;, sometimes even by & amp;& amp; and this problem repeats in some of the cases. Once this conversion thing happens, image file is not created properly.
How it can be resolved?
Same code was working alright from past year, this problem begin to arise from last month only....
Following is the code for saving the images at server end :
foreach($_POST as $key => $value) {
$_POST[$x] = $value;
}
$base=$_REQUEST['image'];
$nm=$_REQUEST['name'];
$binary=base64_decode($base);
if(file_exists("uploaded_images/".$nm.".jpg")) {
unlink("uploaded_images/".$nm.".jpg");
}
header('Content-Type: bitmap; charset=utf-8');
$str="uploaded_images/".$nm.".jpg";
$file = fopen($str, 'wb');
fwrite($file, $binary);
fclose($file);
chmod($file,0777);
$ok=1;
echo $ok;
Following is the error log which is encountered if image is not properly saved.
PHP Notice: Undefined index: name in /var/www/html/cbd/def/filesubmitnew.php
Note : filesubmitnew.php is the file name of the above code.
In Android Application for this is how the url is called:
To Create image:
if(buttontext.equals("Img1")) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
v.setImageBitmap(bitmap);
buttontext="";
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, stream);
byte [] byte_arr = stream.toByteArray();
String str1 = Base64.encodeBytes(byte_arr);
System.out.println(""+str1);
if(feuser.equals("offline_access")){
System.out.println("++==--SD CARD");
File externalStorage = Environment.getExternalStorageDirectory();
File folder = new File(externalStorage.getAbsolutePath() +mainFolder + caseId);
if (!folder.exists()) {
folder.mkdir();
}
File pictureFile = new File(externalStorage.getAbsolutePath()+mainFolder+caseId, "1.jpg");
System.out.println(pictureFile);
pictureFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(pictureFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(str1);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing SD "+pictureFile,Toast.LENGTH_SHORT).show();
}
else {
Intent i = new Intent ("com.keyboardlabs.newbankge.CameraUploadService");
try {
i.putExtra("imageparams", str1);
i.putExtra("ref_id", caseId);
i.putExtra("imageId", "1");
i.putExtra("CaseType",caseType);
}
catch (Exception e) {
e.printStackTrace();
}
getApplicationContext().startService(i);
}
Following is the camerauploadservice
protected void onHandleIntent(Intent arg0) {
String imageDataBase64encoded = arg0.getStringExtra("imageparams");
String caseID = arg0.getStringExtra("ref_id");
String imageId = arg0.getStringExtra("imageId");
String caseType =arg0.getStringExtra("CaseType");
System.out.println("image_ref="+caseID+"iamgeID="+imageId+"caseType="+caseType+" URL="+URL);
callWebService(imageDataBase64encoded,caseID,imageId,caseType);
}
public void callWebService(String imageData,String refId,String imageId,String caseType){
HttpClient httpclient = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",imageData));
nameValuePairs.add(new BasicNameValuePair("ref_id",refId));
nameValuePairs.add(new BasicNameValuePair("imageId",imageId));
nameValuePairs.add(new BasicNameValuePair("CaseType",caseType));
try{
httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String the_string_response = convertResponseToString(response);
System.out.println( "Response= " + the_string_response);
}catch(Exception e){
System.out.println( "0" + e.getMessage());
System.out.println("Error in http connection "+e.toString());
}
httpclient.getConnectionManager().shutdown();
}
Related
I have encoded an image to base 64 as
Bitmap bitmapOrg= BitmapFactory.decodeFile(imagePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] byarray = bao.toByteArray();
String myimage=Base64.encodeBytes(byarray);
.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://10.1.1.5/connect/royal.php");
try{
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
nameValuePairs.add(new BasicNameValuePair("IMAGE",myimage));
nameValuePairs.add(new BasicNameValuePair("FILENAME",trID));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String responseStr = EntityUtils.toString(response.getEntity());
Log.d("chddeck", responseStr);
JSONObject jsonObj = new JSONObject(responseStr);
int success = jsonObj.getInt("success");
if (success == 1) {
status="1";
}else if (success==0){
status="0";
}
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
in php, I have stored as:
$base = $_REQUEST['image'];
$filename = $_REQUEST['filename'];
$buffer=base64_decode($base);
$path = "upload/".$filename.".jpg";
$handle = fopen($path, 'wb');
$numbytes = fwrite($handle, $buffer);
fclose($handle);
$query = $link->prepare("UPDATE transaction evidenceimage=?,evidencename=? WHERE transactionID = '5'");
$values = array($path, $filename);
$query->execute($values);
$counts= $query->rowCount();
if ($counts>0)
{
$rowset = $query->fetchAll();
$response["comments"]=array();
$comments =array();
$response["success"]=1;
}
else{
$response["success"]=0;
}
echo json_encode($response);
Problem is, image is perfectly uploaded in the "upload/" directory in server. But not stored in mysql. In mysql - evidenceimage is set to be "BLOB. After this query, "BLOB-filenameB" is stored in the table, which appears to be only 1 KB.
Please could anybody suggest what am i doing wrong ??
To get the image in your android program I think you need to pass the path of image uploaded in your localhost or the server. And to get the image at your application try this:
UrlImageViewHelper.setUrlDrawable("your imageview name",
"your image path in localhost or server",
"optional image to display if not available in your drawable folder",
"cache duration");
you can get the library UrlImageViewHelper here:
http://www.koushikdutta.com/UrlImageViewHelper
I am using HttpClient to make a request from my Android device to a simple HTTP server, which contains a PHP script to retrieve a picture. The picture is available inside a blob data. It means if I do this little PHP code in the server side:
file_put_contents("myPicture.png", $blob_data);
I get the picture saved in the server with a file named myPicture.png. Now I want to get this $blob_data (my picture) to save it inside my Android device, not the HTTP server. Someone can give me a hint to return the blob data from the PHP script and get the picture inside the Android device to store it locally?
Here is my HTTPClient:
#Click(R.id.btn_login)
#Background
public void LoginTrigger(){
String nUsername = username.getText().toString().trim();
String nPassword = password.getText().toString().trim();
if (nUsername.matches("") || nPassword.matches("")){
displayToast("Please insert your login!");
}
else{
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("username", nUsername));
urlParameters.add(new BasicNameValuePair("password", nPassword));
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(SERVER_PROXY);
post.setHeader("User-Agent", SERVER_USER_AGENT);
try{
post.setEntity(new UrlEncodedFormEntity(urlParameters, "utf-8"));
}
catch(Exception e){
Log.getStackTraceString(e);
}
HttpResponse response = null;
try{
response = client.execute(post);
Log.e("Response Code : ", " = " + response.getStatusLine().getReasonPhrase());
InputStream inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
String responseMessage = sb.toString();
checkLogin(responseMessage);
}
catch(Exception e){
Log.e("HTTP-ERROR", " = " + Log.getStackTraceString(e));
displayToast("Check your Internet connection!");
}
}
}
String responseMessage contains my blob data when I echo it in my PHP script. I just need to put this stream inside a Bitmap or something, but I've no clue about how to get it done.
Thanks if you know it!
php code (server)
<?php
header('Content-Type: image/png');
echo($blob_data);
?>
java code (device)
URL url = new URL ("http://myserver.com/myPicture.png");
InputStream input = url.openStream();
try {
//The sdcard directory e.g. '/sdcard' can be used directly, or
//more safely abstracted with getExternalStorageDirectory()
File storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream (new File(storagePath,"myPicture.png"));
try {
byte[] buffer = new byte[aReasonableSize];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You need to change both the client and the server code.
The server code
Add this at the end of your PHP script
header("Content-Type: image/png");
header("Content-Length: " . mb_strlen($blob_data, '8bit'));
echo $blob_data;
exit;
The client code
Your code is not ready to read binary data, please, check out this other question on how to do it: how to download image from any web page in java
it's not recommended to send the actual file to your android app , the best way to do that is by sending a base 64 encoded a link string of the image , which will have all the meta data of the image , then load the image from base46 encoded string
$image = base64_decode($file_path);
return response::json(array('image'=>$image);
and receive it like object and render your image with the base64code image like this
i do it in js like this
var reader = new FileReader();
reader.onload = function(e) {
image_base64 = e.target.result;
preview.html("<img src='" + image_base64 + "'/>");
};
reader.readAsDataURL(file);
I'm trying to upload an image and some text via MultipartEntity.
I can upload and receive the image, but when I try to add a Stringbody I cannot seem to receive it.
Here's my android code
imports ETC...
public void oncreate(){
.....
nameValuePairs.add(new BasicNameValuePair("image", exsistingFileName));
nameValuePairs.add(new BasicNameValuePair("title", "title"));
}
public void post(String url, List<NameValuePair> nameValuePairs) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int index=0; index < nameValuePairs.size(); index++) {
if(nameValuePairs.get(index).getName().equalsIgnoreCase("image")) {
System.out.println("post - if");
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart( nameValuePairs.get(index).getName(), new FileBody(new File (nameValuePairs.get(index).getValue())));
} else {
System.out.println("post - else");
// Normal string data
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
}
}
System.out.println("post - done" + entity);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
} catch (IOException e) {
e.printStackTrace();
}
}
And my php:
<?php
$uploads_dir = 'uploads/';
$uploadname = $_FILES["image"]["name"];
$uploadtitle = $_FILES["title"]["title"];
move_uploaded_file($_FILES['image']['tmp_name'], $uploads_dir.$uploadname);
file_put_contents($uploads_dir.'juhl.txt', print_r($uploadtitle, true));
?>
I've been around the other questions about MultipartEntity, but cannot seem to find the answer. I've tried sending just the Stringbody, but didn't have any succs in that either. I think the problem is serverside (in the PHP) but any suggestions are welcome.
This is my first question in here - feel free to comment on form and clarity :-)
try this way ,
ByteArrayBody bab1 = bab11;
HttpClient httpClient = new DefaultHttpClient();
httpPost = new HttpPost("link.php?api_name=api");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
// this is for String
try {
reqEntity.addPart("udid", new StringBody(UDID));
}
catch (Exception e)
{
}
// this is for image upload
try
{
reqEntity.addPart("file1", bab1);
} catch (Exception e)
{
}
// this is for video upload
try {
if (stPath1 != null) {
Log.e("path 1", stPath1);
Log.v("stDocType1", "video");
File file = new File(stPath1);
FileBody bin = new FileBody(file);
reqEntity.addPart("file1", bin);
}
} catch (Exception e) {
}
httpPost.setEntity(reqEntity);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
The problem was i the php.
When you receive Stringbody there is only one parametre(as opposed to filebody). So I removed the second parametre in $uploadtitle = $_FILES["title"]["title"]; and it worked
<?php
$uploads_dir = 'uploads/';
$uploadname = $_FILES["image"]["name"];
$uploadtitle = $_FILES["title"];
move_uploaded_file($_FILES['image']['tmp_name'], $uploads_dir.$uploadname);
file_put_contents($uploads_dir.'juhl.txt', print_r($uploadtitle, true));
?>
I hope this helps if you have the same problem.
The below is the runtime exeception which i got while am trying to upload a image to the server.
And am trying to upload a image using my local server(WAMP) and my android code is
Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/Sunset.jpg");
// Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.background1);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",image_str));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.49/android/upload_image.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String the_string_response = convertResponseToString(response);
Toast.makeText(uploadimage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();
}catch(Exception e){
Toast.makeText(uploadimage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();
System.out.println("Error http connection"+e.toString());
}
}
public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{
String res = "";
StringBuffer buffer = new StringBuffer();
inputStream = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
Toast.makeText(uploadimage.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();
if (contentLength < 0){
}
else{
byte[] data = new byte[512];
int len = 0;
try
{
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len)); //converting to string and appending to stringbuffer…..
}
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
inputStream.close(); // closing the stream…..
}
catch (IOException e)
{
e.printStackTrace();
}
res = buffer.toString(); // converting string buffer to string
Toast.makeText(uploadimage.this, "Result : " + res, Toast.LENGTH_LONG).show();
//System.out.println("Response => " + EntityUtils.toString(response.getEntity()));
}
return res;
}
}
and this is my php code which i got from internet .
<?php
$base=$_REQUEST['image'];
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('uploaded_image.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
echo 'Image upload complete!!, Please check your php file directory……';
?>
Can any one help me in this to solve my problem. thanks in advance
You have to create one additional directory in c:\ then provide read, write and execute permission on it.
In your php code please write the absolute path of the storage location.
This may solve your problem.
Remember to run the IIS server in Administrator mode.
Inetpub is created by the SYSTEM user. This means that you aren't allowed to make modifications to it, or any of its subdirectories, without admin permissions. Try changing the permissions of the inetpub folder so anyone can modify the files. Right-click -> Properties -> ... I forget what to do after that. (I'm in Linux right now). If that doesn't work, make sure you are running IIS as an Administrator.
I have used some code from the internet for uploading image
public class ActUpload extends Activity {
InputStream is;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.blue);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeBytes(ba);
ArrayList<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",ba1));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://127.0.0.1:80/php/base.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());
}
}
}
and even took some php code copied some php code which i am running in local sever using wamp server. There is no response in the local server.
and this is my php code.
<?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>';
?>
Can any one help me in this. thanks in advance.
A nice tutorial for uploading image to server-
http://coderzheaven.com/2011/04/android-upload-an-image-to-a-server/
Edit:
You just need to change this according to your local server:
HttpPost httppost = new HttpPost("http://<local ip address>/android/upload_image.php");
// For example,in my code,i used:
// HttpPost httppost = new HttpPost("http://192.168.100.47/android/upload_image.php");
Did you manage to solve the problem? I did get it to work when i changed $base=$_REQUEST['image']; => $base=$_POST['image']; and commented out the following line header('Content-Type: bitmap; charset=utf-8'); Btw, did try to convert the code to use HttpURLConnection api?