dongzhunqiu4841
2015-10-03 00:38
浏览 82

将图像从android上传到php服务器无法正常工作

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

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douzhang3822 2015-10-03 05:35
    已采纳

    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.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题