How to Upload images to Php server and store in phpmyadmin - php

I am basically tring to upload image from android and upload it to php server but here i'm not getting any connection with this code or image upload .
I'm getting this error .
Error in http connection java.net.UnknownHostException: host name
but as per my knowledge i given correct connection and php file also in correct domain.
Look at my code :
UploadImage.java
public class UploadImage extends Activity {
InputStream inputStream;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);
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://server.com/uploadimage/uploadimage.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 in 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 stringbuffer to string…..
Toast.makeText(UploadImage.this, "Result : " + res, Toast.LENGTH_LONG).show();
//System.out.println("Response => " + EntityUtils.toString(response.getEntity()));
}
return res;
}
}
Php Code :
<?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……';?>
Any one known this issue ? if any one know how to store in mysql database from php file and fetch viceversa please suggest me here...

The problem is very clear ...
Error in http connection java.net.UnknownHostException: host name
means that the HttpPost cannot make a connection using the hostname you supplied - because the hostname you supplied isn't known.
If you take the hostname from this line :
HttpPost httppost = new HttpPost("http://server.com/uploadimage/uploadimage.php");
and put it in a browser on the same device what happens ... i suggest you will get an error saying unable to connect to host. If this works then i suggest you check the following line is in your manifest :
<uses-permission android:name="android.permission.INTERNET" />
Also ensure that the PHP file contains the following header if your using a JPEG:
header('Content-Type: image/jpg');

1. Need to add Internet permission in android manifest file .
<uses-permission android:name="android.permission.INTERNET" />
2. Every Time i used to see image using url but unable to see because i didnt added
echo "<img src=test.jpg>";
3.$file = fopen('test.jpg', 'wb');
4. final thing is i have to change header file as :
header('Content-Type: image/jpg; charset=utf-8');

Check Host configuration and choose right header for file upload. In your php code you have given wrong header type.

I recommend you as ManseUK said to add the permission in your Manifest.
This error is quite unclear but is often resolved by adding <uses-permission android:name="android.permission.INTERNET" />

This works for me:
// change the bitmap compress format to jpeg
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
// then uploadimage.php
// note the imagecreatefromstring() function
error_reporting(E_ALL); // in case its turned off and your not seeing errors
ini_set('display_errors','1'); // confirm and browse to page
if($base) {
$ttime = intval(time());
$quality = '100';
$save_to = 'images/img-' . $ttime . '.jpeg';
$binary=base64_decode($base);
$im = imagecreatefromstring($binary);
if ($im !== false) {
header('Content-Type: image/jpg');
$idno = ImageJPEG($im, $save_to, $quality);
imagedestroy($im);
echo "iid:" . $ttime;
} else {
echo "Error:" . $ttime;
}
}

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

empty $_POST and $_FILES with request type multipart/form-data

I'm trying to send post request from android application to server. In this request I want to send some text data (json) and picture.
But I can't get this data in server. Variables $_FILES, $_POST and even php://input is empty. But data is really transferred to server, because in $_SERVER I can find this:
[REQUEST_METHOD] => POST
[CONTENT_TYPE] => multipart/form-data; boundary=Jq7oHbmwRy8793I27R3bjnmZv9OQ_Ykn8po6aNBj; charset=UTF-8
[CONTENT_LENGTH] => 53228
What is the problem can be with this?
server is nginx 1.1
PHP Version 5.3.6-13ubuntu3.10
file_uploads = On
Here is my android code
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(30000)
.setConnectionRequestTimeout(30000)
.setSocketTimeout(30000)
.setProxy(getProxy())
.build();
CloseableHttpClient client = HttpClientBuilder.create()
.setDefaultRequestConfig(config)
.build();
HttpPost post = new HttpPost("http://example.com");
try {
JSONObject root = new JSONObject();
root.put("id", id);
if (mSettings != null) {
root.put("settings", SettingsJsonRequestHelper.getSettingsJson(mSettings));
}
MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
File screenshot = getScreenshotFile();
if (screenshot.exists()) {
builder.addPart("screenshot", new FileBody(screenshot, ContentType.create("image/jpeg")));
}
builder.addTextBody("data", root.toString(), ContentType.create("text/json", Charset.forName("UTF-8")));
builder.setCharset(MIME.UTF8_CHARSET);
post.setEntity(builder.build());
} catch (JSONException e) {
Logger.getInstance().log(e);
}
try {
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
mResponse.setResponse(response.getEntity().getContent());
} else {
Logger.getInstance().log("response error. Code " + response.getStatusLine().getStatusCode());
}
} catch (ClientProtocolException e) {
Logger.getInstance().log(e);
} catch (IOException e) {
Logger.getInstance().log(e);
}
Maybe you have te change php.ini parameters like enable_post_data_reading=on increase post_max_size and upload_max_filesize
Not sure of the method you are using and you did not include your server side processing file. Error may be from either one. But try this. I first send it a file path through the params and named it 'textFileName'.
#Override
protected String doInBackground(String... params) {
// File path
String textFileName = params[0];
String message = "This is a multipart post";
String result =" ";
//Set up server side script file to process it
HttpPost post = new HttpPost("http://10.0.2.2/test/upload_file_test.php");
File file = new File(textFileName);
//add image file and text to builder
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("uploaded_file", file, ContentType.DEFAULT_BINARY, textFileName);
builder.addTextBody("text", message, ContentType.DEFAULT_BINARY);
//enclose in an entity and execute, get result
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
System.out.println("Response: " + s);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return message;
}
Server side php looks like:
<?php
$target_path1 = "uploads/";
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$status = "";
if(isset($_FILES["uploaded_file"])){
echo "Files exists!!";
// if(isset($_POST["text"])){
// echo "The message files exists! ".$_POST["text"];
// }
$target_path1 = $target_path1 . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path1)) {
$status= "The first file ". basename( $_FILES['uploaded_file']['name']).
" has been uploaded.";
}
else{
$status= "There was an error uploading the file, please try again!";
$status.= "filename: " . basename( $_FILES['uploaded_file']['name']);
$status.= "target_path: " .$target_path1;
}
}else{
echo "Nothing in files directory";
}
$array["status"] = "status: ".$status;
$json_object = json_encode($array);
echo $json_object;
?>

How to retrieve a photo from HttpClient?

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);

& converted into & when $_POST request is called?

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();
}

Runtime exception while uploading image to the server

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.

Categories