2013-02-28 49 views
0

我想将图像上传到PHP服务器。我一直试图超过48小时而没有成功。 现在我正在尝试以下操作,但是当按下发送按钮时,应用程序会崩溃。将.png图像上传到PHP服务器

send.setOnClickListener(new OnClickListener() { 

    @Override 
    public void onClick(View v) { 
     try { 
      bm = BitmapFactory.decodeFile("/sdcard/DCIM/android_1.png"); 
      ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
      bm.compress(CompressFormat.JPEG, 75, bos); 
      byte[] data = bos.toByteArray(); 
      HttpClient httpClient = new DefaultHttpClient(); 
      HttpPost postRequest = new HttpPost("XXXXXXXXXXXXXXXXXXXXX/uploads/fileup.php"); 
      ByteArrayBody bab = new ByteArrayBody(data, "android_1.jpg"); 
      ; 
      // File file= new File("/mnt/sdcard/forest.png"); 
      // FileBody bin = new FileBody(file); 
      MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
      reqEntity.addPart("uploadedfile", bab); 
      reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf")); 
      postRequest.setEntity(reqEntity); 
      HttpResponse response = httpClient.execute(postRequest); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); 
      String sResponse; 
      StringBuilder s = new StringBuilder(); 
      Toast.makeText(getApplicationContext(), "your file is saved .",Toast.LENGTH_LONG).show(); 

      while ((sResponse = reader.readLine()) != null) { 
       s = s.append(sResponse); 
      } 
      System.out.println("Response: " + s); 
     } catch (Exception e) { 
      // handle exception here 
      Log.e(e.getClass().getName(), e.getMessage()); 
     } 
    } 
}); 

这里是logcat的:

03-01 12:46:37.638: D/dalvikvm(379): GC_EXTERNAL_ALLOC freed 57K, 49% free 2750K/5379K, external 1625K/2137K, paused 91ms 
03-01 12:46:37.797: D/dalvikvm(379): GC_EXTERNAL_ALLOC freed 1K, 49% free 2749K/5379K, external 3125K/3903K, paused 71ms 
03-01 12:46:38.557: D/dalvikvm(379): GC_EXTERNAL_ALLOC freed 4K, 49% free 2781K/5379K, external 4813K/4813K, paused 86ms 
03-01 12:52:02.326: W/KeyCharacterMap(379): No keyboard for id 0 
03-01 12:52:02.326: W/KeyCharacterMap(379): Using default keymap: /system/usr/keychars/qwerty.kcm.bin 
03-01 12:52:14.986: D/dalvikvm(379): GC_EXTERNAL_ALLOC freed 192K, 47% free 3050K/5703K, external 5112K/6294K, paused 68ms 
03-01 12:52:15.146: D/dalvikvm(379): GC_EXTERNAL_ALLOC freed 7K, 47% free 3043K/5703K, external 6612K/8257K, paused 73ms 
03-01 12:52:18.866: D/AndroidRuntime(379): Shutting down VM 
03-01 12:52:18.866: W/dalvikvm(379): threadid=1: thread exiting with uncaught exception (group=0x40015560) 
03-01 12:52:18.886: E/AndroidRuntime(379): FATAL EXCEPTION: main 
03-01 12:52:18.886: E/AndroidRuntime(379): java.lang.NullPointerException: println needs a message 
03-01 12:52:18.886: E/AndroidRuntime(379): at android.util.Log.println_native(Native Method) 
03-01 12:52:18.886: E/AndroidRuntime(379): at android.util.Log.e(Log.java:230) 
03-01 12:52:18.886: E/AndroidRuntime(379): at tracking.android.TrackingActivity$1.onClick(TrackingActivity.java:84) 
03-01 12:52:18.886: E/AndroidRuntime(379): at android.view.View.performClick(View.java:2485) 
03-01 12:52:18.886: E/AndroidRuntime(379): at android.view.View$PerformClick.run(View.java:9080) 
03-01 12:52:18.886: E/AndroidRuntime(379): at android.os.Handler.handleCallback(Handler.java:587) 
03-01 12:52:18.886: E/AndroidRuntime(379): at android.os.Handler.dispatchMessage(Handler.java:92) 
03-01 12:52:18.886: E/AndroidRuntime(379): at android.os.Looper.loop(Looper.java:130) 
03-01 12:52:18.886: E/AndroidRuntime(379): at android.app.ActivityThread.main(ActivityThread.java:3683) 
03-01 12:52:18.886: E/AndroidRuntime(379): at java.lang.reflect.Method.invokeNative(Native Method) 
03-01 12:52:18.886: E/AndroidRuntime(379): at java.lang.reflect.Method.invoke(Method.java:507) 
03-01 12:52:18.886: E/AndroidRuntime(379): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 
03-01 12:52:18.886: E/AndroidRuntime(379): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 
03-01 12:52:18.886: E/AndroidRuntime(379): at dalvik.system.NativeStart.main(Native Method) 
+1

邮政logcat的请。 – Egor 2013-02-28 13:50:11

+0

日志猫信息... – 2013-02-28 13:50:56

+0

试图发布logcat,但我得到这个: – 2013-02-28 14:46:55

回答

0

谢谢大家的回应...我发现这个链接 http://www.coderzheaven.com/2012/04/26/upload-image-android-device-server-method-4/ 我改变了我的android代码和php,也许它有助于某人。

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
    <Button 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="Upload File" 
     android:id="@+id/but" 
    /> 

    <TextView 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="@string/hello" 
     android:id="@+id/tv" 
     android:textColor="#00FF00" 
     android:textStyle="bold" 
    /> 
</LinearLayout> 

这里是Android部分

TextView tv; 
Button b; 
int serverResponseCode = 0; 
ProgressDialog dialog = null; 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    b = (Button)findViewById(R.id.but); 
    tv = (TextView)findViewById(R.id.tv); 
    tv.setText("Uploading file path :- '/sdcard/android_1.png'"); 

    b.setOnClickListener(new OnClickListener() {    
     @Override 
     public void onClick(View v) { 
      dialog = ProgressDialog.show(UploadImageDemo.this, "", "Uploading file...", true); 
      new Thread(new Runnable() { 
        public void run() { 
         runOnUiThread(new Runnable() { 
           public void run() { 
            tv.setText("uploading started....."); 
           } 
          });      
        int response= uploadFile("/sdcard/android_1.png"); 
        System.out.println("RES : " + response);       
        } 
        }).start();   
      } 
    }); 
} 

public int uploadFile(String sourceFileUri) { 
     String upLoadServerUri = "http://10.0.2.2/upload_test/upload_media_test.php"; 
     String fileName = sourceFileUri; 

     HttpURLConnection conn = null; 
     DataOutputStream dos = null; 
     String lineEnd = "\r\n"; 
     String twoHyphens = "--"; 
     String boundary = "*****"; 
     int bytesRead, bytesAvailable, bufferSize; 
     byte[] buffer; 
     int maxBufferSize = 1 * 1024 * 1024; 
     File sourceFile = new File(sourceFileUri); 
     if (!sourceFile.isFile()) { 
     Log.e("uploadFile", "Source File Does not exist"); 
     return 0; 
     } 
      try { // open a URL connection to the Servlet 
      FileInputStream fileInputStream = new FileInputStream(sourceFile); 
      URL url = new URL(upLoadServerUri); 
      conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL 
      conn.setDoInput(true); // Allow Inputs 
      conn.setDoOutput(true); // Allow Outputs 
      conn.setUseCaches(false); // Don't use a Cached Copy 
      conn.setRequestMethod("POST"); 
      conn.setRequestProperty("Connection", "Keep-Alive"); 
      conn.setRequestProperty("ENCTYPE", "multipart/form-data"); 
      conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); 
      conn.setRequestProperty("uploaded_file", fileName); 
      dos = new DataOutputStream(conn.getOutputStream()); 

      dos.writeBytes(twoHyphens + boundary + lineEnd); 
      dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + lineEnd); 
      dos.writeBytes(lineEnd); 

      bytesAvailable = fileInputStream.available(); // create a buffer of maximum size 

      bufferSize = Math.min(bytesAvailable, maxBufferSize); 
      buffer = new byte[bufferSize]; 

      // read file and write it into form... 
      bytesRead = fileInputStream.read(buffer, 0, bufferSize); 

      while (bytesRead > 0) { 
      dos.write(buffer, 0, bufferSize); 
      bytesAvailable = fileInputStream.available(); 
      bufferSize = Math.min(bytesAvailable, maxBufferSize); 
      bytesRead = fileInputStream.read(buffer, 0, bufferSize);    
      } 

      // send multipart form data necesssary after file data... 
      dos.writeBytes(lineEnd); 
      dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 

      // Responses from the server (code and message) 
      serverResponseCode = conn.getResponseCode(); 
      String serverResponseMessage = conn.getResponseMessage(); 

      Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); 
      if(serverResponseCode == 200){ 
       runOnUiThread(new Runnable() { 
        public void run() { 
         tv.setText("File Upload Completed."); 
         Toast.makeText(UploadImageDemo.this, "File Upload Complete.", Toast.LENGTH_SHORT).show(); 
        } 
       });     
      }  

      //close the streams // 
      fileInputStream.close(); 
      dos.flush(); 
      dos.close(); 

     } catch (MalformedURLException ex) { 
      dialog.dismiss(); 
      ex.printStackTrace(); 
      Toast.makeText(UploadImageDemo.this, "MalformedURLException", Toast.LENGTH_SHORT).show(); 
      Log.e("Upload file to server", "error: " + ex.getMessage(), ex); 
     } catch (Exception e) { 
      dialog.dismiss(); 
      e.printStackTrace(); 
      Toast.makeText(UploadImageDemo.this, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show(); 
      Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e); 
     } 
     dialog.dismiss();  
     return serverResponseCode; 
    } 
} 
1

嘿,我可以看到你正在使用多实体upploading的形象,所以,当你这样做 而不是

MultipartEntity reqEntity = new MultipartEntity(
      HttpMultipartMode.BROWSER_COMPATIBLE); 
    reqEntity.addPart("uploadedfile", bab); 
    reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf")); 
    postRequest.setEntity(reqEntity); 

此密码请尝试以下代码

MultipartEntity reqEntity = new MultipartEntity(
      HttpMultipartMode.BROWSER_COMPATIBLE); 
    FileBody mImage=new FileBody(new File(path)); // The path here is the path of the 
                // image either coming from the 
                //camera or gallery 
    reqEntity.addPart("uploadedfile", mImage); 
    reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf")); 
    postRequest.setEntity(reqEntity); 
+0

谢谢你......但它一样..它不断崩溃..请任何帮助 – 2013-02-28 15:07:58

+0

嘿尝试发布logcat。我猜是因为应用程序崩溃的空指针异常。并且这里唯一可能的空值是路径,尝试给出正确的路径,我的意思是像从画廊或相机中选择的动态值。如果你可以发布logcat的例外部分,我可以帮助你进一步。 :) – Droidee 2013-02-28 15:20:48

+0

couldnt设法从日食得到catlog,这就是为什么我通过catlog查看器从设备中得到它...... – 2013-02-28 16:51:01