0

I am having trouble with the file being properly decoded or maybe even encoded. I am trying to send an image to a php server via volley from an android device. I am able to generate the image file from php but it shows up as corrupted and doesn't show an image at all. Here is my code from android.

//Send image to server

            String url = "http://www.urlhere.com/test.php";

            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);


                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream);
                byte[] byteArray = byteArrayOutputStream.toByteArray();

                final String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);

                StringRequest postRequest = new StringRequest(Request.Method.POST, url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                try {
                                    JSONObject jsonResponse = new JSONObject(response).getJSONObject("form");
                                    String site = jsonResponse.getString("site"),
                                            network = jsonResponse.getString("network");
                                    System.out.println("Site: " + site + "\nNetwork: " + network);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                error.printStackTrace();
                            }
                        }
                ) {
                    @Override
                    protected Map<String, String> getParams() {
                        Map<String, String> params = new HashMap<>();
                        // the POST parameters:
                        params.put("picture", encoded);
                        return params;
                    }
                };
                Volley.newRequestQueue(getApplicationContext()).add(postRequest);

            } catch (IOException e) {
                e.printStackTrace();
            }


        }

And here is the PHP side of it, first I send it to a php page to put the string into a text file then I use this code to try to convert it to an image file.

$file = file_get_contents('test.txt', true);

$filePath = "file.jpg";
$myfile = fopen($filePath, "w") or die("Unable to open file!");

file_put_contents($filePath, base64_decode($file));

Now when the text file is created, it adds picture= to the front of the base 64 string and an ampersand at the end. I remove both of these manually right now in order to decode the string but no luck.

Please help me out, I would really appreciate it. Thank You.

UPDATE

Here is the updated code, I am using still does not work.

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.media.Image;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class showImage extends AppCompatActivity {

ImageView imageView;
ImageButton imageButton;
String encodedString;
String fileName;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show_image);

    imageView = (ImageView)findViewById(R.id.imageView);

    final Uri selectedImage = getIntent().getData();


    Glide.with(this).load(selectedImage).fitCenter().into(imageView);

    imageButton = (ImageButton)findViewById(R.id.imageButton);

    imageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            String fileNameSegments[] = picturePath.split("/");
            fileName = fileNameSegments[fileNameSegments.length - 1];

            Bitmap myImg = BitmapFactory.decodeFile(picturePath);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            // Must compress the Image to reduce image size to make upload easy
            myImg.compress(Bitmap.CompressFormat.PNG, 50, stream);
            byte[] byte_arr = stream.toByteArray();
            // Encode Image to String
            encodedString = Base64.encodeToString(byte_arr, 0);

            uploadImage();




        }
    });

}

public void uploadImage() {

    RequestQueue rq = Volley.newRequestQueue(getApplicationContext());
    String url = "http:/www.testurl.com/test.php";
    Log.d("URL", url);
    StringRequest stringRequest = new StringRequest(Request.Method.POST,
            url, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            try {
                Log.e("RESPONSE", response);
                JSONObject json = new JSONObject(response);

                Toast.makeText(getBaseContext(),
                        "The image is upload", Toast.LENGTH_SHORT)
                        .show();

            } catch (JSONException e) {
                Log.d("JSON Exception", e.toString());
                Toast.makeText(getBaseContext(),
                        "Error while loadin data!",
                        Toast.LENGTH_LONG).show();
            }

        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("ERROR", "Error [" + error + "]");
            Toast.makeText(getBaseContext(),
                    "Cannot connect to server", Toast.LENGTH_LONG)
                    .show();
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();

            params.put("image", encodedString);
            params.put("filename", fileName);

            return params;

        }

    };
    rq.add(stringRequest);
}





@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_show_image, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

Solankill
  • 3
  • 2
  • 7
  • Does your Server have a Shared-Host ?? – Adeel Ahmad Sep 19 '15 at 06:52
  • Have you read http://stackoverflow.com/questions/16797468/how-to-send-a-multipart-form-data-post-in-android-with-volley/31718902#31718902? – BNK Sep 19 '15 at 07:04
  • Yes the Server has a shared host. And I am not sure how I would integrate your code into my app @BNK – Solankill Sep 19 '15 at 19:00
  • Dont integrate it. make a new project and test this code buy sending some image on server, if it works with your shared host server, then proceed... – Adeel Ahmad Sep 19 '15 at 19:57

1 Answers1

0

Considering that you are not using a Web-server for this purpose but a VPS, try this tutorial, i've tried it myself and it worked like a charm. This too, uses Volley :

http://team.158ltd.com/2015/04/30/how-to-upload-image-to-php-server-android/

If problem remains, we'll discuss here in comments.Best of Luck !

Adeel Ahmad
  • 990
  • 8
  • 22
  • Thank You for your help, unfortunately it still does not seem to work. Also it is not a VPS it is an actual server, and I do believe it is shared. When I tried your code standalone it works, but if I try to integrate it into my app it does not. Also my adb.exe keeps crashing when I try to run it on my phone now. I will update the code above with the newly integrated. – Solankill Sep 19 '15 at 18:51
  • Bro. i was a having bit different having problem. The link i gave you, this code worked perfectly when i tried it on local server with my phone and computer connected over same network ( using MAMP/XAMPP) but since i have server with shared host, i was getting a 0KB file on server. i could not figure it out and found it a dead end so i had to move on FTP for transferring files until i buy some VPS. – Adeel Ahmad Sep 19 '15 at 19:50
  • I suggest you to try this code, try to dig deeper into the problem, but if shared-host is the problem ( thats what i suspect, like mine) then there is no solution for that. if you are ok with FTP , i wrote this library from the code i wrote for myself :) , i'll be happy to guide you : https://android-arsenal.com/details/1/2499 – Adeel Ahmad Sep 19 '15 at 19:53
  • So the only alternate right now is to try using the FTP? I am giving this current project a break and working on another one, hopefully if I get away for a while I can figure it out once I am back. Thanks again for your help, I will update you soon once I get back on track! – Solankill Sep 22 '15 at 16:29
  • if your problem is "shared-host" then Yes. and considering accepting the answer if it helped :) – Adeel Ahmad Sep 22 '15 at 16:39