2012-06-10 301 views
1

我試圖將從手機相機拍攝的圖像上傳到服務器。由於我是在Android上傳圖片的新手,所以對此不甚瞭解。我在Google上搜索了一篇關於互聯網的教程,它可以作爲一個獨立的應用程序工作,但是當我在我的應用程序中使用同一個類時,它不再工作。我在我的logcat中遇到了錯誤(我將在本文結尾處發佈)。我不知道這個錯誤意味着什麼,我該如何解決這個問題。請幫助我如何做這項工作?android將圖像上傳到服務器

這裏是我的相機活動代碼

public class Camera extends Activity { 
ImageView ivUserImage; 
Button bUpload; 
Intent i; 
int CameraResult = 0; 
Bitmap bmp; 
FileUpload fu; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.camera); 

    ivUserImage = (ImageView)findViewById(R.id.ivUserImage); 
    bUpload = (Button)findViewById(R.id.bUpload); 
    openCamera(); 
} 

private void openCamera() { 
    i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
    startActivityForResult(i, CameraResult); 
} 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

    super.onActivityResult(requestCode, resultCode, data); 
    if(resultCode == RESULT_OK) { 
     Bundle extras = data.getExtras(); 
     //Log.e("Image: ", data.toString()); 
     bmp = (Bitmap) extras.get("data"); 
     ivUserImage.setImageBitmap(bmp); 

     bUpload.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       //Toast.makeText(getApplicationContext(), bmp.toString(), Toast.LENGTH_SHORT).show(); 
       fu = new FileUpload(bmp.toString()); 
      } 
     }); 
    } 
} 

} 

這裏是我的FileUpload類

public class FileUpload extends Activity { 
TextView tv; 
Button b; 
int serverResponseCode = 0; 
ProgressDialog dialog = null; 

public FileUpload(final String bmp) { 
    dialog = ProgressDialog.show(FileUpload.this, "", "Uploading file...", true); 
    new Thread(new Runnable() { 
      public void run() { 
       runOnUiThread(new Runnable() { 
         public void run() { 
          tv.setText("uploading started....."); 
         } 
        }); 
      int response= uploadFile(bmp); 
      //Log.e("Response: ", response); 
      System.out.println("RES : " + response); 
      } 
     }).start(); 
} 

public int uploadFile(String sourceFileUri) { 
    String upLoadServerUri = "http://www.example.info/androidfileupload/index.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(FileUpload.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(FileUpload.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(FileUpload.this, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show(); 
    Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e); 
} 
dialog.dismiss(); 
return serverResponseCode; 

} }

,這裏是我在我的logcat得到

06-10 14:26:55.320: W/IInputConnectionWrapper(23770): showStatusIcon on inactive InputConnection 
06-10 14:27:03.765: D/AndroidRuntime(23770): Shutting down VM 
06-10 14:27:03.765: W/dalvikvm(23770): threadid=1: thread exiting with uncaught exception (group=0x4001e578) 
06-10 14:27:03.775: E/AndroidRuntime(23770): FATAL EXCEPTION: main 
06-10 14:27:03.775: E/AndroidRuntime(23770): java.lang.IllegalStateException: System services not available to Activities before onCreate() 
06-10 14:27:03.775: E/AndroidRuntime(23770): at android.app.Activity.getSystemService(Activity.java:3562) 
06-10 14:27:03.775: E/AndroidRuntime(23770): at android.app.Dialog.<init>(Dialog.java:141) 
06-10 14:27:03.775: E/AndroidRuntime(23770): at android.app.AlertDialog.<init>(AlertDialog.java:63) 
06-10 14:27:03.775: E/AndroidRuntime(23770): at android.app.ProgressDialog.<init>(ProgressDialog.java:80) 
06-10 14:27:03.775: E/AndroidRuntime(23770): at android.app.ProgressDialog.<init>(ProgressDialog.java:76) 
06-10 14:27:03.775: E/AndroidRuntime(23770): at android.app.ProgressDialog.show(ProgressDialog.java:101) 
06-10 14:27:03.775: E/AndroidRuntime(23770): at android.app.ProgressDialog.show(ProgressDialog.java:90) 
06-10 14:27:03.775: E/AndroidRuntime(23770): at com.zafar.login.FileUpload.<init>(FileUpload.java:25) 
06-10 14:27:03.775: E/AndroidRuntime(23770): at com.zafar.login.Camera$1.onClick(Camera.java:52) 
06-10 14:27:03.775: E/AndroidRuntime(23770): at android.view.View.performClick(View.java:2538) 
06-10 14:27:03.775: E/AndroidRuntime(23770): at android.view.View$PerformClick.run(View.java:9152) 
06-10 14:27:03.775: E/AndroidRuntime(23770): at android.os.Handler.handleCallback(Handler.java:587) 
06-10 14:27:03.775: E/AndroidRuntime(23770): at android.os.Handler.dispatchMessage(Handler.java:92) 
06-10 14:27:03.775: E/AndroidRuntime(23770): at android.os.Looper.loop(Looper.java:130) 
06-10 14:27:03.775: E/AndroidRuntime(23770): at android.app.ActivityThread.main(ActivityThread.java:3691) 
06-10 14:27:03.775: E/AndroidRuntime(23770): at java.lang.reflect.Method.invokeNative(Native Method) 
06-10 14:27:03.775: E/AndroidRuntime(23770): at java.lang.reflect.Method.invoke(Method.java:507) 
06-10 14:27:03.775: E/AndroidRuntime(23770): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907) 
06-10 14:27:03.775: E/AndroidRuntime(23770): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665) 
06-10 14:27:03.775: E/AndroidRuntime(23770): at dalvik.system.NativeStart.main(Native Method) 
+0

您是否在Android Mainifest中設置了所有必需的權限? – libjup

+0

我認爲它需要'<使用權限android:name =「android.permission.INTERNET」/>'我的網絡權限 – 2619

+0

您將主要Activity的上下文傳遞給此Upload類。 –

回答

1

您使用new創建Object FileUpload活動。在Android中,建議將活動設計爲獨立模塊,並且該活動由Android創建。如果你想與其他活動交流,你應該使用意圖來做到這一點。

fu = new FileUpload(bmp.toString()); // here make error. 

在android中不可能創建另一個活動的對象。

+0

是的,我不希望這個班是一個活動。我想創建一個全新的類,即類FileUpload {}。但是,當我改變它顯示噸錯誤。我的意思是有這麼多線紅色下劃線。 – 2619

+0

public FileUpload(Context context,final String bmp)dialog = ProgressDialog.show(context,「」,「上傳文件...」,true); 新主題(新的Runnable(){ 公共無效的run(){ runOnUiThread(新的Runnable(){ 公共無效的run(){ tv.setText( 「上傳開始......」);} }); int response = uploadFile(bmp); //Log.e("Response:「,response); System.out.println(」RES:「+ response); } })。start ); }和fu = new FileUpload(this,bmp.toString()); –

+0

我沒有收到你的評論。這是什麼意思?你能詳細說明一下嗎? – 2619

0

我建議你創建一個FTP服務器並使用ftp來上傳你的文件。以下代碼是從FTP服務器獲取文件的方法。定製它的上傳:

public static boolean getFile(String serverName, String userName, 
     String password, String serverFilePath, String localFilePath) 
     throws Exception { 

    FTPClient ftp = new FTPClient(); 

    try { 
     // ftp.setCopyStreamListener(); 

     ftp.connect(serverName); 
     int reply = ftp.getReplyCode(); 

     if (!FTPReply.isPositiveCompletion(reply)) { 
      ftp.disconnect(); 
      return false; 
     } 
    } catch (IOException e) { 
     if (ftp.isConnected()) { 
      try { 
       ftp.disconnect(); 
      } catch (IOException f) { 
       throw e; 
      } 
     } 
     throw e; 
    } catch (Exception e) { 
     throw e; 
    } 

    try { 
     // String filePath = "system/mswin.98/SETUP0.WAV"; 
     if (!ftp.login(userName, password)) { 
      ftp.logout(); 
     } 
     // if (binaryTransfer) 
     ftp.setFileType(FTPClient.BINARY_FILE_TYPE); 
     // ftp.enterLocalPassiveMode(); 
     ftp.enterLocalActiveMode(); 

     OutputStream output; 

     if (checkAndCreateDirectories(localFilePath)) { 
      output = new FileOutputStream(localFilePath); 
      ftp.retrieveFile(serverFilePath, output); 
      output.close(); 
     } 

     ftp.noop(); // check that control connection is working OK 
     ftp.logout(); 
     return true; 

    } catch (FTPConnectionClosedException e) { 
     throw e; 
    } catch (IOException e) { 
     throw e; 
    } catch (Exception e) { 
     throw e; 
    } finally { 
     if (ftp.isConnected()) { 
      try { 
       ftp.disconnect(); 
      } catch (IOException f) { 
       throw f; 
      } 
     } 

    } 

} 
+0

ftp是否比我目前使用的更好? – 2619

+0

我認爲這很容易。 – breceivemail

+0

你可以控制用戶訪問 – breceivemail

相關問題