2013-11-27 11 views
0

我想通過後PHP發送圖像和字符串。我已經添加外部罐httpclientandroidlib-1.1.2.jar但它一直崩潰,我試着兩個代碼下面但仍然崩潰。下面的代碼需要snapsot,然後按下按鈕上傳它應該上傳。我真的很感激任何幫助。感謝提前。上傳圖像和字符串發佈方法android(ics)

Button btn=(Button)findViewById(R.id.snapshot); 
     btn.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 

       Intent i=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
       startActivityForResult(i, 0); 

      } 
     }); 

     uploadButton=(Button)findViewById(R.id.uploadButton); 

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

        if (finalFile!=null) { 

         HttpPost httpost = new HttpPost("http://example/test.php"); 
         MultipartEntity entity = new MultipartEntity(); 
         try { 
          entity.addPart("name", new StringBody("test")); 
         } catch (UnsupportedEncodingException e1) { 
          // TODO Auto-generated catch block 
          e1.printStackTrace(); 
         } 
         entity.addPart("image", new FileBody(finalFile)); 

         httpost.setEntity(entity); 
         HttpResponse response; 
         HttpClient httpclient = null; 
         try { 
          response = httpclient.execute(httpost); 
         } catch (ClientProtocolException e) { 
          // TODO Auto-generated catch block 
          e.printStackTrace(); 
         } catch (IOException e) { 
          // TODO Auto-generated catch block 
          e.printStackTrace(); 
         } 

        } 
       }}); 


    } 


    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     // TODO Auto-generated method stub 
    // super.onActivityResult(requestCode, resultCode, data); 

     if (requestCode==0) { 

      if (data!=null) { 


       Bitmap bt=(Bitmap) data.getExtras().get("data"); 

       Uri tempUri = getImageUri(getApplicationContext(), bt); 

       finalFile = new File(getRealPathFromURI(tempUri)); 

      } 

     } 


    } 


public Uri getImageUri(Context inContext, Bitmap inImage) { 
    ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes); 
    String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null); 
    return Uri.parse(path); 
} 

public String getRealPathFromURI(Uri uri) { 
    Cursor cursor = getContentResolver().query(uri, null, null, null, null); 
    cursor.moveToFirst(); 
    int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
    return cursor.getString(idx); 
} 

而且下面的代碼不工作我已經試過這兩個代碼:

    HttpClient httpclient = new DefaultHttpClient(); 
        HttpPost httppost = new HttpPost(
          "http://example/test.php"); 

        try { 
         MultipartEntity entity = new MultipartEntity(); 

         entity.addPart("name", new StringBody("test")); 
         entity.addPart("image", new FileBody(finalFile)); 

         httppost.setEntity(entity); 
         HttpResponse response = httpclient.execute(httppost); 

         Log.e("test", "SC:" + response.getStatusLine().getStatusCode()); 

         HttpEntity resEntity = response.getEntity(); 

         BufferedReader reader = new BufferedReader(new InputStreamReader(
           response.getEntity().getContent(), "UTF-8")); 
         String sResponse; 
         StringBuilder s = new StringBuilder(); 

         while ((sResponse = reader.readLine()) != null) { 
          s = s.append(sResponse); 
         } 
         Log.e("test", "Response: " + s); 
     } catch (ClientProtocolException e) { 
       } catch (IOException e) { 
       } 

其中一個logcat的錯誤:

FATAL EXCEPTION: main 
java.lang.NoClassDefFoundError: ch.boye.httpclientandroidlib.client.methods.HttpPost 
    at com.example.MainActivity$2.onClick(MainActivity.java:158) 
    at android.view.View.performClick(View.java:3549) 
    at android.view.View$PerformClick.run(View.java:14393) 
    at android.os.Handler.handleCallback(Handler.java:605) 
    at android.os.Handler.dispatchMessage(Handler.java:92) 
    at android.os.Looper.loop(Looper.java:154) 
    at android.app.ActivityThread.main(ActivityThread.java:4945) 
    at java.lang.reflect.Method.invokeNative(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:511) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 
    at dalvik.system.NativeStart.main(Native Method) 

對於其他代碼:

FATAL EXCEPTION: main 
android.os.NetworkOnMainThreadException 
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1178) 
    at java.net.InetAddress.lookupHostByName(InetAddress.java:394) 
    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:245) 
    at java.net.InetAddress.getAllByName(InetAddress.java:220) 
    at ch.boye.httpclientandroidlib.impl.conn.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:45) 
    at ch.boye.httpclientandroidlib.impl.conn.DefaultClientConnectionOperator.resolveHostname(DefaultClientConnectionOperator.java:278) 
    at ch.boye.httpclientandroidlib.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:162) 
    at ch.boye.httpclientandroidlib.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:294) 
    at ch.boye.httpclientandroidlib.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:645) 
    at ch.boye.httpclientandroidlib.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:480) 
    at ch.boye.httpclientandroidlib.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:902) 
    at ch.boye.httpclientandroidlib.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:801) 
    at ch.boye.httpclientandroidlib.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:780) 
    at com.example1.MainActivity$2.onClick(MainActivity.java:133) 
    at android.view.View.performClick(View.java:3549) 
    at android.view.View$PerformClick.run(View.java:14393) 
    at android.os.Handler.handleCallback(Handler.java:605) 
    at android.os.Handler.dispatchMessage(Handler.java:92) 
    at android.os.Looper.loop(Looper.java:154) 
    at android.app.ActivityThread.main(ActivityThread.java:4945) 
    at java.lang.reflect.Method.invokeNative(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:511) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 
    at dalvik.system.NativeStart.main(Native Method) 

PHP文件:

<?php 
$name=$_POST['name']; 
$file = $_FILES['image']; 
if (isset($name)) 
{ 
     $connect=mysql_connect("localhost","localhost","localhost") or die ('Connection error!!!'); 
     mysql_select_db("localhost") or die ('Database error!!!'); 
     $file_path = "/localhost/localhost/"; 

       if(move_uploaded_file($file, $file_path)) { 
       $query1=("INSERT INTO example(name,link) VALUES ('$name','$file_path')"); 

      $query=mysql_query($query1) or die(mysql_error()); 
      $json_output ='{"test":{"test":"'.$file.'"}}'; 
       } 

     echo trim($json_output); 
     mysql_close($connect) or die ('Unable to close the connection!!!');;   
} 
?> 
+0

發佈您的logcat,因爲它崩潰! –

+0

@LazyNinja我已更新所有代碼 – jason

回答

0
android.os.NetworkOnMainThreadException 
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1178) 
    at java.net.InetAddress.lookupHostByName(InetAddress.java:394) 

意味着你正在嘗試做的主線程上的網絡操作。
使用AsyncTask()來設計這些操作。

僅用於測試目的,您可以在setcontentview之後添加以下內容以查看代碼是否有效。

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
StrictMode.setThreadPolicy(policy); 

確保您的代碼正常工作後,使用AsyncTask,因爲嚴格不鼓勵使用StrictMode!

+0

我的php代碼是否正確?請告訴我>感謝您查看它。 – jason

+0

我試過了你現在沒有崩潰的代碼,但也沒有上載圖像,也沒有在表格中輸入數據。 – jason