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

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

Related

php connection with android project

I am a beginner in android development. I want to connect a php file to the android app. My php code is
<?php
$con = mysqli_connect("localhost", "root", "", "invoice_db");
if(mysqli_connect_errno($con)) {
echo "Failed to connect";
}
$response["sucess"]=0;
$invoiceid = $_POST['invc'];
$response = array();
$sql = "SELECT sl_no from invoice_table where invoice_id='$invoiceid'";
$result = mysqli_query($con,$sql);
if(!empty($result)) {
$row = mysqli_fetch_array($result);
$data = $row[0];
$response["sucess"] = 1;
}
mysqli_close($con);
?>
Here 'invc' is get from httpRequest ,
JSONObject json = jsonParser.makeHttpRequest(url_check_user, "POST", params);
And my JSONParser page contains,
if (method == "POST") {
// request method is POST
// defaultHttpClient
System.out.println("Inside json parser POST condition");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
System.out.println("Inside json parser POST condition" + params);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
Log.d("From httpentity", httpEntity.toString());
System.out.println("ppppppppppppphhhhhhhhhhhhhhhhhhhhppppppppppp");
is = httpEntity.getContent();
}
Now I want to check , whether the parameters were passed to the php page or not. So I want to console/log cat the $invoiceid. How can it possible in Eclipse Ide?
If you want to print a variable inside PHP code, you can do echo $variable. However please note that PHP code will be executed on a server and not on your android device. Moreover your PHP code is vulnerable to sql injection attacks
You can use JSON encoding method in your php file to get a proper JSON response like this.
$response = array (
'invoiceid' => $verify_code,
);
print json_encode($response);
which will return a JSON string to your app in a format like
{"invoiceid":"null"}
which you can decode and log it like this
InputStreamReader isw = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isw);
String line = "";
StringBuffer buffer = new StringBuffer();
while ((line = br.readLine()) != null){
buffer.append(line);
}
String finalresult = buffer.toString();
JSONObject myobject = new JSONObject(finalresult);
String flag= myobject.getString("invoiceid");
log.e("mylog",flag)
so that it will be visible in your logcat file.

Android image upload not getting to PHP script

I'm trying to upload an image from Android to a PHP server.
Here is my upload code:
public static void uploadFile(final String imagePath){
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(SERVER);
try {
File imageFile = new File(imagePath);
httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, System.getProperty("http.agent"));
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("image", new FileBody(imageFile));
httpPost.setEntity(entity.build());
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(resEntity.getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
} catch (IOException e) {
e.printStackTrace();
}
}
Here is my PHP code for handling the upload:
<?php
echo "FILES - ";
var_dump($_FILES);
echo " REQUEST - ";
var_dump($_REQUEST);
$file_path = "images";
$file_path = $file_path . basename($_FILES['image']['name']);
if(move_uploaded_file($_FILES['image']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
?>
I'm getting 200 responses from the page, but the $_FILES and $_REQUEST variables are both empty. It seems that the image file is not making it to the script, and I have no idea why. I'm doing it right according to all the tutorials I've found.
The images I'm uploading are ~180kb
Any ideas?
This was a problem with my server. I switched to using a different sub-domain of my server, and it's working perfectly now.

php for receiving image and text from MultipartEntity

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.

HTTP post from android to PHP not working

I am trying to get a Android device to send some information to a local host. I believe I have the Android sending the information, but my PHP code is not accepting or not displaying the code. I have attached my code, is there something I have missed? I am running wamp server also, and have put the permissions into the manifest.
Java Code: #
HttpPost httppost;
HttpClient httpclient;
// List with arameters and their values
List<NameValuePair> nameValuePairs;
String serverResponsePhrase;
int serverStatusCode;
String bytesSent;
String serverURL = "http://10.0.2.2/test/index.php";
httppost = new HttpPost(serverURL);
httpclient = new DefaultHttpClient();
nameValuePairs = new ArrayList<NameValuePair>(2);
// Adding parameters to send to the HTTP server.
nameValuePairs.add(new BasicNameValuePair("parameterName1", "git"));
nameValuePairs.add(new BasicNameValuePair("parameterName2", "git"));
// Send POST message with given parameters to the HTTP server.
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
InputStream is = response.getEntity().getContent();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(20);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
bytesSent = new String(baf.toByteArray());
// Response from the server
serverResponsePhrase = response.getStatusLine().getReasonPhrase();
serverStatusCode = response.getStatusLine().getStatusCode();
System.out.println("COMPLETE");
} catch (Exception e) {
// Exception handling
System.out.println("Problem is " + e.toString());
}
PHP Code:
<?php
echo "param1 value: ".$_POST['parameterName1']."\n";
echo "param2 value: ".$_POST['parameterName2']."\n";
?>
I also tried this code, but it did not work with my PHP
HttpPost httppost;
HttpClient httpclient;
// List with arameters and their values
List<NameValuePair> nameValuePairs;
String serverResponsePhrase;
int serverStatusCode;
String bytesSent;
String serverURL = "http://10.0.2.2/test/index.php";
httppost = new HttpPost(serverURL);
httpclient = new DefaultHttpClient();
nameValuePairs = new ArrayList<NameValuePair>(2);
// Adding parameters to send to the HTTP server.
nameValuePairs.add(new BasicNameValuePair("'parameterName1'", "git"));
nameValuePairs.add(new BasicNameValuePair("'parameterName2'", "git"));
// Send POST message with given parameters to the HTTP server.
try {
HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs);
httppost.addHeader(entity.getContentType());
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
InputStream is = response.getEntity().getContent();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(20);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
bytesSent = new String(baf.toByteArray());
// Response from the server
serverResponsePhrase = response.getStatusLine().getReasonPhrase();
serverStatusCode = response.getStatusLine().getStatusCode();
System.out.println("response" + response.toString());
System.out.println("COMPLETE");
} catch (Exception e) {
// Exception handling
System.out.println("Problem is " + e.toString());
}
Make sure the Content-Type HTTP header is getting set. Try replacing
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
with this
HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs);
httppost.addHeader(entity.getContentType());
httppost.setEntity(entity);
Also, instead of response.toString(), try EntityUtils.toString(response.getEntity()) if you want to see the body of the response

How to upload video to PHP SERver from Android

Hi Guys i m using following code but getting error0 as response . Please help in following code as i m near to success.
public void video()
{
File file = new File(exsistingFileName);
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://10.0.0.27/sportscloud/devices/uploadBlogData.php";
HttpPost post = new HttpPost(postURL);
FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("email", new StringBody("test1#nga.com", "text/plain", Charset.forName( "UTF-8")));
reqEntity.addPart("gameId", new StringBody("1024", "text/plain", Charset.forName( "UTF-8")));
reqEntity.addPart("source", new StringBody("phone", "text/plain", Charset.forName("UTF-8")));
reqEntity.addPart("uploadfile",bin );
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
Log.i("RESPONSE",EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
}
what kind of error do you get? more info will be helpfull :)
try this
InputStream is = this.getAssets().open(exsistingFileName);
byte[] data = IOUtils.toByteArray(is);
InputStreamBody isb = new InputStreamBody(new ByteArrayInputStream(data),"uploadedFile");
reqEntity.addPart("uploadfile",isb);
good luck

Categories