php for receiving image and text from MultipartEntity - php

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.

Related

sending a value with HttpPost object

I would like to send a value to the end of a url.
ex:
if I have id=1;, I want to send this id to end of my url (to obtain id) :
www.example.com/get/id
id values ​​are different. (ex:id=2;id=3;id=4...).
is it possible ? how can I use HttpPost for this Scenario ?
I am using these functions but I always get this message :
no parametrs was sended !
inside my url :
www.example.com/get/id :
function get($id=0){
$id = (int)$id;
if(!$id) exit("no parametrs was sended !");
$trac = $this->m_general->get('tractions' , array('id' => $id ) , true );
if(!$trac ) $resp = "-1";
else
if($trac->expired != 0 || $trac->cradit_end_date < date('Y-m-d'))
{
$resp = 0;
}else
$resp = 1;
echo json_encode(array('response'=>$resp));
}
function set(){
$data = $this->input->post('data');
if(!$data) exit("no parametrs was sended !");
$message = $data;
$message = substr($message,7,-6);
list($qr,$date,$time) = explode("&",$message);
$insert = array(
'qr'=>$qr ,
'date'=>$date ,
'time'=>$time ,
'main'=>$message
);
$this->m_general->add('qr' , $insert );
}
private void postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(this.url_server_side);
HttpResponse response = null;
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("data", valueIWantToSend));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
String res = EntityUtils.toString(response.getEntity());
Log.e("Response = ", res);
isok = 1 ;
} catch (ClientProtocolException e) {
e.printStackTrace();
// TODO Auto-generated catch block
isok = -1 ;
} catch (IOException e) {
e.printStackTrace();
// TODO Auto-generated catch block
isok = -1 ;
}
//Log.e("res", response.toString()) ;
}
As you mentioned above your web application expecting GET method to pass variables. In java code you are sending a POST request. You should use GET method to pass data.
String url = "http://www.example.com/id/YOUR_ID_DATA/data/YOUR_DATA";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("User-Agent", USER_AGENT);
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
Or send both id, data in a POST request and accept as a POST response from PHP side.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com");
HttpResponse response = null;
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", YOUR_ID_DATA));
nameValuePairs.add(new BasicNameValuePair("data", YOUR_DATA));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Then in PHP Side
$id = $_POST["id"];
$data = $_POST["data"];

Server cannot read json values from Android : Undifined IINdex and json null received at Server

I am going to implement the client-to-Server module which request is sent from Android devices to php . When it comes to the implementation , I have no clue why the server side cannot receive the json sent from Android device . As for the server, the database insert module is OK but cannot catch the json values . Would you please tell me what is wrong with the client side ?
The below is my code
Client side Android
public String postData(String argument , String url) {
String result="";
// Create a new HttpClient and Post Header
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 60000 * 20;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 60000 * 20;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
HttpConnectionParams.setSocketBufferSize(httpParameters, 8*1024);
DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
//Log.d("url" , url);
HttpPost httppost = new HttpPost(url);
try {
System.out.println("Response:"+ "start execute");
JSONObject json = new JSONObject();
json.put("userid","loka");
json.put("password","yoor");
json.put("email","johnsmith#example.com");
//Log.d("test" , jsonString);
httppost.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
httppost.setHeader( "Content-Type", "application/json" );
//httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
//If php json response required
if(status==200){
HttpEntity getResponseEntity = response.getEntity();
InputStream httpResponseStream = getResponseEntity.getContent();
result = slurp(httpResponseStream , 8192);
System.out.println("result: "+ result);
}else{
System.out.println("2");
result = String.valueOf(status);
HttpEntity getResponseEntity = response.getEntity();
InputStream httpResponseStream = getResponseEntity.getContent();
result = slurp(httpResponseStream , 8192);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
return e.getMessage();
} catch (ConnectTimeoutException e){
e.printStackTrace();
return e.getMessage();
}catch (IOException e) {
e.printStackTrace();
return e.getMessage();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
Server side php
<?php
header('Content-type: application/json');
ini_set('display_errors','On');
require_once 'lib_mysql/insert.php';
$json = file_get_contents('php://input');
$result =insertUser($json);
if($result) {
echo "success";
}
else{
echo "fail";
}
?>
include_once("connection.php");
function insertUser($jsonString){
$usern = $jsonString->userid; //Undefined Variables
$pass = $jsonString->password; //Undefined Variables
$email = $jsonString->email; //Undefined Variables
$conn = getDBConn();
$data = false;
You need to use json_decode() function in php. header('Content-type: application/json'); would not help in this case
Try this way hope this helps you
Relpace
httppost.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
with
httppost.setEntity(new StringEntity(json.toString(), HTTP.UTF_8));

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.

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

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