2016-10-07 12 views
1

アンドロイドアプリからサーバーに画像をアップロードするコードをPHPで作成しようとしています。何らかの理由でアンドロイドアプリからサーバーに画像をアップロードすることはできません

<?php 
$json = file_get_contents('php://input'); 
$obj = json_decode($json); 
$imageEncoded = $obj->{"imageEncoded"} 

$image = base64_decode("$imageEncoded"); 

$alterName = rand(); 
$target= $_SERVER['DOCUMENT_ROOT']."/imagenes/"; 
$new_img_path =$target.$alterName.".jpg";    

file_put_contents($new_img_path, $image);?> 

public class uploadImage extends AsyncTask< String, String, String>{ 

    Bitmap _image; 

    uploadImage(Bitmap image){ 
     _image = image; 
    } 

    @Override 
    protected String doInBackground(String... params) { 
     HttpURLConnection con = null; 
     BufferedOutputStream os= null; 

     try { 

      URL url = new URL("URL_TO_SERVER"); 
      con = (HttpURLConnection) url.openConnection(); 

      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 
      _image.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream); 
      byte[] byte_arr = byteArrayOutputStream.toByteArray(); 
      String _imageEncoded = Base64.encodeToString(byte_arr, Base64.DEFAULT); 

      JSONObject jsonObject = new JSONObject(); 
      jsonObject.put("imageEncoded", _imageEncoded); 
      String message = jsonObject.toString(); 

      con.setDoOutput(true); 
      con.setRequestProperty("Content-Type", "application/json;charset=utf-8"); 
      con.setRequestProperty("X-Requested-With", "XMLHttpRequest"); 
      con.connect(); 

      os = new BufferedOutputStream(con.getOutputStream()); 
      os.write(message.getBytes()); 
      os.flush(); 

      return ""; 


     } catch (IOException e) { 
      e.printStackTrace(); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     finally { 
      if (con != null) 
       con.disconnect(); 
      if (os != null) 
       try { 
        os.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
     } 

     return null; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     super.onPostExecute(result); 
    } 
}//uploadImage 

これは、PHPのコードです:私はによってはBase64に変換し、これは、Javaコードで文字列

としてそれを送るそれをしようとしていますそれはちょうどうまくいかない、誰かが私のエラーが何であるか教えてくれますか?より良いアプローチで私を導くことができます。

+0

:ここ

ByteArrayOutputStream outStream = new ByteArrayOutputStream(); yourBitmap.compress(Bitmap.CompressFormat.JPEG, 90, outStream); byte[] bArray = outStream.toByteArray(); String imgEncoding = Base64.encodeBytes(bArray); 

は、そのクラスへのリンクです。 – dipali

+0

しかし、JSON形式でデータを送信できないのですか?それともそれを変更することを提案しますか? – Disturb

+0

ログをログに記録する – Shane

答えて

関連する問題