File is not being uploaded properly - php

In my android app, I've to upload file to server and read the file at server side. File is being uploaded but some times what happen, in folder (at server in which file resides) if previously uploaded file exists, then the current uploaded file is generated with previous file data. e.g. say if I upload file named A to server with data say '1, 2 and 3' then there will be file A.txt under folder at server side with same data, and if now I upload file named B to server with data say 'A, B and C' then file B.txt under folder will be there but with previous file data of A.txt. So in B.txt, data is '1, 2 and 3'. Below is my code. What can be the issue?
Android Side
public void uploadUserFriendId(String user_id, String filePath, String fileName)
{
String server_url = "http://addressofserver/folder/myfile.php";
InputStream inputStream;
try
{
inputStream = new FileInputStream(new File(filePath));
byte[] data;
try
{
data = IOUtils.toByteArray(inputStream);
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
System.getProperty("http.agent"));
HttpPost httpPost = new HttpPost(server_url);
InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data), fileName);
MultipartEntity multipartEntity = new MultipartEntity();
multipartEntity.addPart("file", inputStreamBody);
multipartEntity.addPart("user_id", new StringBody(user_id));
httpPost.setEntity(multipartEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
// Handle response back from script.
if(httpResponse != null) {
//Toast.makeText(getBaseContext(), "Upload Completed. ", 2000).show();
} else { // Error, no response.
//Toast.makeText(getBaseContext(), "Server Error. ", 2000).show();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
PHP Side
<?php
error_reporting(~0);
ini_set('display_errors', 1);
mysql_connect("localhost", "root", "Admin#123") or die(mysql_error()) ;
mysql_select_db("retail_menu") or die(mysql_error()) ;
$today =date("YmdHis");
$pic=$today.".txt";
if (isset($_POST["user_id"]) && !empty($_POST["user_id"]))
{
$user_id=$_POST['user_id'];
}
else
{
$user_id="null";
}
$objFile = & $_FILES["file"];
// here file is created under folder named upload at server side
if( move_uploaded_file( $objFile["tmp_name"], "upload/".$user_id.".txt" ) )
{
$file = fopen("upload/".$user_id.".txt" ,"r");
while(! feof($file))
{
$friend_id = fgets($file, 8192);
if($friend_id!= null)
{
$query = "INSERT IGNORE INTO table_name (user_id, friend_id) values('$user_id', '$friend_id')";
var_dump($query);
mysql_query($query);
}
}
fclose($file);
}
else
{
print "There was an error uploading the file, please try again!";
}
?>

Related

Upload doc, pdf,xls etc, from android application to php server

I get stuck at that place and unable to send doc file to php server.
I am using this code.
Here is PHP code.
if($_SERVER['REQUEST_METHOD']=='POST'){
$image = $_POST['image'];
$name = $_POST['name'];
require_once('dbConnect.php');
$sql ="SELECT id FROM volleyupload ORDER BY id ASC";
$res = mysqli_query($con,$sql);
$id = 0;
while($row = mysqli_fetch_array($res)){
$id = $row['id'];
}
$path = "uploads/$id.doc";
$actualpath = "http://10.0.2.2/VolleyUpload/$path";
$sql = "INSERT INTO volleyupload (photo,name) VALUES ('$actualpath','$name')";
if(mysqli_query($con,$sql)){
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded";
}
mysqli_close($con);
}else{
echo "Error";
}
Here is Java code
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("file/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
PICK_IMAGE_REQUEST);
}
I called asynTask on upload button.
if (v == buttonUpload) {
// uploadImage();
new PostDataAsyncTask().execute();
}
A function calls in doInBackground is
private void postFile() {
try {
// the file to be posted
String textFile = Environment.getExternalStorageDirectory()
+ "/Woodenstreet Doc.doc";
Log.v(TAG, "textFile: " + textFile);
// the URL where the file will be posted
String postReceiverUrl = "http://10.0.2.2/VolleyUpload/upload.php";
Log.v(TAG, "postURL: " + postReceiverUrl);
// new HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
File file = new File(filePath.toString());
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
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
The exception I get is that
java.io.FileNotFoundException: content:/com.topnet999.android.filemanager/storage/0F02-250A/test.doc: open failed: ENOENT (No such file or directory)
There is file in emulator - test.doc.
Is there is any thing I miss in code, please help me.
Or suggest a tutorial to upload pdf to php server.
Thanks In Advance.
Here is the solution of my question: -
Here is code of php file - file.php
<?php
// DISPLAY FILE INFORMATION JUST TO CHECK IF FILE OR IMAGE EXIST
echo '<pre>';
print_r($_FILES);
echo '</pre>';
// DISPLAY POST DATA JUST TO CHECK IF THE STRING DATA EXIST
echo '<pre>';
print_r($_POST);
echo '</pre>';
$file_path = "images/";
$file_path = $file_path . basename( $_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $file_path)) {
echo "file saved success";
} else{
echo "failed to save file";
}?>
Put this file in htdoc folder of Xampp inside test named folder (if there is test folder already then ok, otherwise make a folder named "test"). And also create a folder named "images", in which uploaded file was saved.
Create function to select file from gallery
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
1);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getActivity(), "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
Inside onActivityResult function
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
Uri selectedFileURI = data.getData();
File file = new File(selectedFileURI.getPath().toString());
Log.d("", "File : " + file.getName());
uploadedFileName = file.getName().toString();
tokens = new StringTokenizer(uploadedFileName, ":");
first = tokens.nextToken();
file_1 = tokens.nextToken().trim();
txt_file_name_1.setText(file_1);
}
}
This is asyncTask to upload file to server,
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(false);
pDialog.setMessage("Please wait ...");
showDialog();
}
#Override
protected String doInBackground(String... strings) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://10.0.2.2/test/file.php");
file1 = new File(Environment.getExternalStorageDirectory(),
file_1);
fileBody1 = new FileBody(file1);
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file1", fileBody1);
httpPost.setEntity(reqEntity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
final String responseStr = EntityUtils.toString(resEntity)
.trim();
Log.v(TAG, "Response: " + responseStr);
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
hideDialog();
Log.e("", "RESULT : " + result);
}
}
Call the asyncTask on button click after selecting the file from gallery.
btn_upload.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new PostDataAsyncTask().execute();
}
});
Hope this will help you.
Happy To Help and Happy Coding.
The code below is not tested ( as is ) but is generally how one might handle the file upload - there is, as you will see, a debug statement in there. Try to send the file and see what you get ~ if all lokks ok, comment out that line and keep your fingers crossed.
<?php
/* Basic file upload handler - untested */
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_FILES['image'] ) && !empty( $_FILES['image']['tmp_name'] ) ){
/* Assuming the field being POSTed is called `image`*/
$name = $_FILES['image']['name'];
$size = $_FILES['image']['size'];
$type = $_FILES['image']['type'];
$tmp = $_FILES['image']['tmp_name'];
/* debug:comment out if this looks ok */
exit( print_r( $_FILES,true ) );
$result = $status = false;
$basename=pathinfo( $name, PATHINFO_FILENAME );
$filepath='http://10.0.2.2/VolleyUpload/'.$basename;
$result=#move_uploaded_file( $tmp, $filepath );
if( $result ){
$sql = "insert into `volleyupload` ( `photo`, `name` ) values ( '$filepath', '$basename' )";
$status=mysqli_query( $con, $sql );
}
echo $result && $status ? 'File uploaded and logged to db' : 'Something not quite right. Uploaded:'.$result.' Logged:'.$status;
}
?>
java.io.FileNotFoundException:
content:/com.topnet999.android.filemanager/storage/0F02-250A/test.doc:
open failed: ENOENT (No such file or directory)
What you have is a content provider path. Not a file system path.
So you cannot use the File... classes.
Instead use
InputStream is = getContentResolver().openInputStream(uri);
For the rest your php code does not make sense as there is no base64 encoding at upload. Further the $path and $actualpath parameters are not used and confusing. And you did not tell what your script should do.

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

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.

Android: How to get image from remote server

I am developing an Android app that should get an image from remote server. Am using WAMP as my server and PHP as programming language. I know how to get text data using JSON.
Am not using blob to store image.
Images have stored in a folder on server. Url of image is stored in db table.
I tried the following snippet, I got this from net but it is not giving any error and also it is not displaying image
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2/sareesProject/returnSareeTypeImageUrls.php");
response = httpClient.execute(httpPost);
entity = response.getEntity();
if(response.getStatusLine().getStatusCode() == 200)
{
Log.d("Http Response:", response.toString());
if(entity != null)
{
InputStream instream = entity.getContent();
JSONObject jsonObj = new JSONObject(convertStreamToString(instream));
String base64Image = jsonObj.getString("pprs");
Toast.makeText(getBaseContext(), base64Image, Toast.LENGTH_LONG).show();
byte[] rawImage = Base64.decode(base64Image, Base64.DEFAULT);
bmp = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length);
}
}
ImageView imageview = (ImageView) findViewById(R.id.flag);
imageview.setImageBitmap(bmp);
The following is my php code
<?php
error_reporting( E_ALL ^ E_NOTICE ^ E_WARNING);
$con = mysql_connect("localhost","root","") or die("con error");
mysql_select_db("sareesdb") or die("db select eror");
$query = mysql_query("select * from noofpiecesinatype");
if($row = mysql_fetch_assoc($query))
{
$response = $row['imageUrl'];
}
$response = base64_encode($response);
echo '{"pprs":'.json_encode($response).'}';
mysqli_close($con);
?>
I checked my php code with html(with out encoding $response value) am getting image there, but not in Android.
I am not good with Php, but if you return the file url via a JSON reponse you can use the following code for downloading the file.
int count;
try {
URL url = new URL("http://url of your file");
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
## Edit ##
After the Image is downloaded you can create a Bitmap from the Image Path/InputStream and assign it to the Image View like this
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
Bitmap bmp = BitmapFactory.decodeStream(bufferedInputStream);
Original source
try {
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://10.0.2.2/sareesProject/returnSareeTypeImageUrls.php");
response = httpClient.execute(httpPost);
entity = response.getEntity();
if(response.getStatusLine().getStatusCode() == 200)
{
Log.d("Http Response:", response.toString());
if(entity != null)
{
instream = entity.getContent();
JSONObject jsonObj = new JSONObject(convertStreamToString(instream));
bitmapPath = jsonObj.getString("pprs");
}
}
try {
Toast.makeText(getBaseContext(), "http://10.0.2.2/sareesProject/"+bitmapPath, Toast.LENGTH_SHORT).show();
URL url = new URL("http://10.0.2.2/sareesProject/"+bitmapPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
bmp = myBitmap;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
if(bmp == null)
Toast.makeText(getBaseContext(), "null", Toast.LENGTH_SHORT).show();
ImageView imageview = (ImageView) findViewById(R.id.flag);
imageview.setImageBitmap(bmp);
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getBaseContext(),e.getMessage(), Toast.LENGTH_LONG).show();
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
//new HomePage().show("in con");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
//show(line);
//new HomePage().show("in while");
//new HomePage().show("l="+line);
sb.append(line+"\n");
}
} catch (IOException e) {
e.printStackTrace();
//Toast.makeText(, text, duration)
} finally {
try {
if(reader != null)
{
try{reader.close();}
catch(Exception e){e.printStackTrace();}
}
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}//end of convertStreamToString
The following is my php code
<?php
error_reporting( E_ALL ^ E_NOTICE ^ E_WARNING);
$con = mysql_connect("localhost","root","") or die("con error");
mysql_select_db("sareesdb") or die("db select eror");
$query = mysql_query("select * from noofpiecesinatype");
$response = array();
while($row = mysql_fetch_assoc($query))
{
$response[] = $row['imageUrl'];
}
echo json_encode($response);
mysqli_close($con);
?>
//--------------------
Fnally i got it.............
First of all my server file returns the following
{"pprs":"upload/22.png"}
from this i extracted upload/22.png using JSON
Now bitmapPath contains upload/22.png
Thank you very much to insomniac giving suggestions.............
If it is helpful to any one vote for me..............

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