Rene Limon
Rene Limon

Reputation: 624

Uploading image from android to php server is not working properly

I´m trying to upload an image using openurlconnection but I´m facing some problems. this is my java class:

public class Upload extends AppCompatActivity
{
    InputStream inputStream;

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

      StrictMode.enableDefaults();

      Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sss);
      ByteArrayOutputStream stream = new ByteArrayOutputStream();
      bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
      byte [] byte_arr = stream.toByteArray();
      String encodedImage = Base64.encodeToString(byte_arr, Base64.DEFAULT);
      String msj = downloadImage(encodedImage);
      Toast.makeText(getBaseContext(), "mensaje "+msj, Toast.LENGTH_SHORT).show();
    }


    public String downloadImage(String tabla)
    {
      String urlG = "http://192.168.43.98/jober/";

      try {
          URL url = new URL(urlG+"upload.php");
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();
          conn.setRequestMethod("POST");

          // para activar el metodo post
          conn.setDoOutput(true);
          conn.setDoInput(true);
          DataOutputStream wr = new DataOutputStream(
                  conn.getOutputStream());
          wr.writeBytes("image="+tabla);
          wr.flush();
          wr.close();

          InputStream is = conn.getInputStream();
          BufferedReader rd = new BufferedReader(new InputStreamReader(is));
          String line;
          StringBuffer response = new StringBuffer();
          while((line = rd.readLine()) != null) {
              response.append(line);
              response.append('\r');
          }
          rd.close();
          return response.toString();
       }
        catch(Exception e){ return "error";}
    }
}

and php code is:

<?php   
    $base=$_REQUEST['image'];
    $binary=base64_decode($base);
    header('Content-Type: bitmap; charset=utf-8');
    $file = fopen('uploaded_image.png', 'wb');
    fwrite($file, $binary);
    fclose($file);
    echo 'Image upload complete!!, Please check your php file directory……';
?>

the only problem is when I check the file and looks like:

enter image description here

I was looking for the error but I´m not able to.

Upvotes: 0

Views: 681

Answers (1)

Raghu Teja
Raghu Teja

Reputation: 225

You have to URLEncode the String before you send it to PHP, since the default base64 decode also includes the symbols + and =. Change

String encodedImage = Base64.encodeToString(byte_arr, Base64.DEFAULT);

to

String encodedImage = URLEncoder.encode(Base64.encodeToString(byte_arr, Base64.DEFAULT), "UTF-8");

and you are good to go.

Upvotes: 1

Related Questions