0

画像を PHP サーバーにアップロードしようとしています。48 時間以上試しましたが、成功しませんでした。現在、次のことを試していますが、送信ボタンを押すとアプリケーションがクラッシュします。

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

ログキャットは次のとおりです。

    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)
4

2 に答える 2

1

画像のアップロードに multiPart エンティティを使用していることがわかります。

  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);
于 2013-02-28T14:11:21.460 に答える
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;  
     } 
}
于 2013-03-02T11:44:31.230 に答える