Android : Upload Image to mysql - php

I want to upload an image file into mysql database on Android Mobile Programming, but I've some problem with it. Here's my code:
My code on Eclipse:
private void uploadFile() {
// TODO Auto-generated method stub
String nama = getIntent().getStringExtra("user");
Bundle fieldresults = this.getIntent().getExtras();
Filepath = fieldresults.getString("bitmap");
Bitmap bitmapOrg= BitmapFactory.decodeFile(Filepath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeBytes(ba);
ArrayList nameValuePairs = new
ArrayList();
nameValuePairs.add(new BasicNameValuePair("image",ba1));
nameValuePairs.add(new BasicNameValuePair("filename",Filepath));
nameValuePairs.add(new BasicNameValuePair("username_user",nama));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://10.0.2.2/BloodGlucose/uploadImage.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 my PHP code:
<?php
include_once("koneksi.php");
$username = $_REQUEST['username_user'];
$hasil = mysql_query("select * from login");
$base = $_REQUEST['image'];
$filename = $_ReQUEST['filename']
$buffer=base64_decode($base);
$path = "img/".$filename.".jpg";
$handle = fopen($path, 'wb');
$numbytes = fwrite($handle, $buffer);
fclose($handle);
$conn=mysql_connect("localhost","root","");
mysql_select_db("db_bloodglucose");
$sql = "UPDATE login SET file = '" . $path . "' Where username_user = $username;
$r=mysql_query($sql);
?>
The problem is the file didn't show in my database (mysql), anyone can help me? thanks before
best regards

Your $sql looks wrong, try:
$sql = "UPDATE login SET file = '$path' WHERE username_user = '$username'";
$r = mysql_query($sql);

this line
$sql = "UPDATE login SET file = '" . $path . "' Where username_user = $username; $r=mysql_query($sql);
should read
$sql = "UPDATE login SET file = '" . $path . "' Where username_user = " . $username; $r=mysql_query($sql);

Related

Storing in BLOB- only 1 KB of data, No image stored

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

Android - best way to upload image to the server using php

I need to upload a bitmap image to my server but it takes a lot of time while uploading. I use base64 to encode the image and decode it while adding it to the database as Blob.
I want to know what is the other alternative way to upload an image and which one is more efficient.
Here what I have been trying:
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);
HttpConnectionParams.setConnectionTimeout(params, 20000);
HttpConnectionParams.setSoTimeout(params, 15000);
DefaultHttpClient httpClient = new DefaultHttpClient(params);
HttpPost httpPost = new HttpPost(url);
namevaluepair.add(new BasicNameValuePair("icon", getStringDrawing(bmIcon)))
httpPost.setEntity(new UrlEncodedFormEntity(namevaluepair));
httpClient.execute(httpPost);
public static String getStringDrawing(Bitmap bm) {
String image_str = "";
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte[] byte_arr;
bm.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte_arr = stream.toByteArray();
image_str = Base64.encodeBytes(byte_arr);
} catch (NullPointerException e) {
}
return image_str;
}
In PHP I tried to save it in Blob and in folder here some of the codes:
$Drawing = $_POST {'drawing'};
$buffer = base64_decode($Drawing);
$file = fopen("PostImage/P".$ID.".png", 'wb');
fwrite($file, $buffer);
fclose($file);
The second try:
$Drawing = $_POST {'drawing'};
$buffer = base64_decode($Drawing);
$buffer = mysql_real_escape_string($buffer);
$query = "INSERT INTO `drawposts` (`PostID`, `UserID`,`DatePost`, `Drawing`) VALUES (NULL,'$UserID','$Date','$buffer')";
$sth = mysql_query($query);
Look at the FileEntity . Something like
File Picture = new File("/path/to/jpg");
FileEntity f = new FileEntity(picture,"application/octet-stream");
HttpPost post = new HttpPost("my URL");
post.setEntity(f);
post.setHeader("Content-type", "application/octet-stream");

Android: Sending file to server : PHP receive that file in server

In my application i have to send the csv file to server
i tried the following code
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
and my php code is..
<?php
if ($_FILES["detection"]["error"] > 0)
{
echo "Return Code: " . $_FILES["detection"]["error"] . "<br>";
}
else
{
if (file_exists($_FILES["detection"]["name"]))
{
echo $_FILES["detection"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["detection"]["tmp_name"],$_FILES["detection"]["name"]);
echo "Stored in: ". $_FILES["detection"]["name"];
}
}
?>
i got the error that
08-26 17:29:18.318: I/edit user profile(700):
08-26 17:29:18.318: I/edit user profile(700): Notice: Undefined index: detection in C:\xampp\htdocs\sendreport.php on line 4
I hope it will work
// the file to be posted
String textFile = Environment.getExternalStorageDirectory() + "/sample.txt";
Log.v(TAG, "textFile: " + textFile);
// the URL where the file will be posted
String postReceiverUrl = "http://yourdomain.com/post_data_receiver.php";
Log.v(TAG, "postURL: " + postReceiverUrl);
// new HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
File file = new File(textFile);
FileBody fileBody = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file", fileBody);
httpPost.setEntity(reqEntity);
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
Log.v(TAG, "Response: " + responseStr);
// you can add an if statement here and do other actions based on the response
}
and php code.
<?php
// if text data was posted
if($_POST){
print_r($_POST);
}
// if a file was posted
else if($_FILES){
$file = $_FILES['file'];
$fileContents = file_get_contents($file["tmp_name"]);
print_r($fileContents);
}
?>

PHP: undefined index error but variable has correct value when printed

I'm passing some values from an android app to a PHP script. I get an undefined index error in my PHP script but the variables have the correct values when I print them out from within the script. I want these errors gone but I can't figure out why they are there in the first place. Here is how they are passed to the PHP script.
Java Code
//build url data to be sent to server
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username",username));
nameValuePairs.add(new BasicNameValuePair("password",password));
String result = "";
InputStream is = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/PasswordCheck.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("Connection", "Error in http connection "+e.toString());
}
PHP Code:
<?php
mysql_connect("localhost", "root", "") or die("could not connect to mysql");
mysql_select_db("drop-in") or die("database not found");
if(isset($_POST["username"])){
$username = $_POST["username"];
}
if(isset($_POST["password"])){
$suppliedPassword = $_POST["password"];
}
$databasePassword = "";
$output = "false";
$query = mysql_query("SELECT Password FROM users WHERE Username = '$username'") or die("query failed");
if(mysql_num_rows($query) > 0){
$row = mysql_fetch_assoc($query);
$databasePassword = $row['password'];
if($databasePassword == $suppliedPassword)
{
$output = "true";
}
}
print($output);
mysql_close();
?>
EDIT: added PHP script (they aren't in the same file, the code tags are misbehaving)
Turns out it was a simple spelling error. I used a lower case 'p' in the word 'password' in my loop instead of an uppercase. Odd that it caused the error that it did.

Posting JSONobjects from android to PHP script

I'm looking to take some data from an android application, post it to a PHP script and then write it into my PostGreSQL database. I'm having some difficulty, could anyone explain why the data is not being transferred. I keep getting a lot of StrictMode violations. I'm hoping that when the user clicks 'Upload' on the app the whole process is automated and the data automatically written to my PGSQL server.
Android application
protected void syncToWebService(final JSONObject json){
HttpClient httpclient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 10000);
HttpResponse response;
String httppost = "http://users.aber.ac.uk/dwd/mfb/php/jsonscript.php";
try
{
HttpPost post = new HttpPost(httppost);
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(), i);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
String ba1=Base64.encodeToString(ba, i);
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("photo", ba1.toString()));
postParameters.add(new BasicNameValuePair("name", resultName.getText().toString()));
postParameters.add(new BasicNameValuePair("description", resultDescription.getText().toString()));
postParameters.add(new BasicNameValuePair("latitude", resultLat.getText().toString()));
postParameters.add(new BasicNameValuePair("longitude", resultLong.getText().toString()));
postParameters.add(new BasicNameValuePair("project", resultProject.getText().toString()));
postParameters.add(new BasicNameValuePair("owner", username));
//response = CustomHttpClient.executeHttpPost(httppost, postParameters);
post.setEntity(new UrlEncodedFormEntity(postParameters));
response = httpclient.execute(post);
/*Checking response variable*/
if(response!=null){
InputStream in = response.getEntity().getContent();
}
}
catch (Exception e){
e.printStackTrace();
}
}
PHP file
$conn = pg_connect("dbconnection_string");
$jsonString = file_get_contents('php://input');
$jsonObj = json_decode($jsonString, true);
if(!empty($jsonObj)) {
try {
$name = jsonObj['name'];
$desc = jsonObj['description'];
$latitude = jsonObj['latitude'];
$longitude = jsonObj['longitude'];
$project = jsonObj['project'];
$owner = jsonObj['owner'];
}
}
//decode photo string
$photo = $_REQUEST["photo"];
echo $photo;
$binary=base64_decode($photo);
header('Content-Type: bitmap; charset=utf-8');
$id = pg_query("SELECT * FROM users WHERE email = $owner");
$id_assoc = pg_fetch_assoc($id);
$id_res = $id_assoc['u_id'];
$res = pg_query("INSERT INTO records (photo, name, description, latitude, longitude, project, owner) VALUES ('$photo', '$name', '$desc', '$latitude', '$longitude', '$project', '$id_res'");
pg_close($conn);
Any help you can give would be much appreciated.
change this, you missed $ in jsonObj
try {
$name = jsonObj['name'];
$desc = jsonObj['description'];
$latitude = jsonObj['latitude'];
$longitude = jsonObj['longitude'];
$project = jsonObj['project'];
$owner = jsonObj['owner'];
}
to
try {
$name = $jsonObj['name'];
$desc = $jsonObj['description'];
$latitude = $jsonObj['latitude'];
$longitude = $jsonObj['longitude'];
$project = $jsonObj['project'];
$owner = $jsonObj['owner'];
}

Categories