2015-10-03 69 views
0

我試圖使用openurlconnection上傳圖像,但我遇到了一些問題。這是我的java類:將圖像從android上傳到php服務器無法正常工作

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";} 
    } 
} 

和PHP代碼爲:

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

唯一的問題是,當我檢查文件,看起來像:

enter image description here

我一直在尋找對於錯誤,但我不能。

回答

1

因爲默認的base64解碼還包含符號+和=,所以在將它發送到PHP之前,您必須對字符串進行URLEn編碼。 更改

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

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

,你是好去。

+0

對不起,這是對的。我的代碼現在正在工作, –

相關問題