2012-06-10 3 views
1

휴대 전화 카메라에서 가져온 이미지를 서버에 업로드하려고합니다. 안드로이드에서 이미지를 업로드하는 것이 처음 인 이래서 이것에 대해 많이 알지 못합니다. 인터넷에서 분리형 앱으로 작동하는 인터넷 검색 후 튜토리얼을 따랐지만 내 앱에서 동일한 클래스를 사용하면 더 이상 작동하지 않습니다. 내 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; 

} }입니다

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

내가 사용했던 ' 인터넷 허가가 필요하다고 생각합니다. – 2619

+0

주 활동의 컨텍스트를이 업로드 클래스로 전달합니다. –

답변

1

new을 사용하여 Object FileUpload 활동을 생성합니다. Android에서는 액티비티가 독립 실행 형 모듈로 설계되고 Android에서 활동이 생성되도록 제안됩니다. 다른 활동과 의사 소통하기를 원한다면, 이것을하기 위해 의도를 사용해야합니다.

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

안드로이드에서는 다른 활동의 개체를 만들 수 없습니다.

+0

그래, 나는이 수업을 활동으로 삼기를 원치 않는다. 나는 완전히 새로운 클래스, 즉 FileUpload 클래스를 만들고 싶었다. 그러나 내가 그것을 바꿨을 때 그것은 많은 오류를 보여 줬다. 빨간색 밑줄이 너무 많다는 뜻입니다. – 2619

+0

공개 FileUpload (컨텍스트 컨텍스트, 최종 문자열 bmp) { dialog = ProgressDialog.show (컨텍스트, ""파일 업로드 중 ... ", true); 새로운 스레드 (새의 Runnable는() { 공공 무효 실행() { runOnUiThread (새의 Runnable() { 공공 무효 실행() { tv.setText는() "업로드가 ..... 시작"; } (응답 : "+ 응답); } }); 시작 (); } 및 fu = 새 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

관련 문제