1

我正在尝试将从手机摄像头拍摄的图像上传到服务器。由于我是在 android 中上传图像的新手,因此我对此知之甚少。在谷歌搜索后,我在互联网上遵循了一个教程,它确实可以作为一个单独的应用程序工作,但是当我在我的应用程序中使用同一个类时,它不再工作了。我的 logcat 中出现错误(我将在本文末尾发布)。我不知道这个错误是什么意思,我该如何解决这个问题。请帮助我如何使这项工作?

这是我的相机活动代码

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

2 回答 2

1

Object FileUpload使用new. 在Android中,建议将Activity设计成一个独立的模块,由Android创建。如果您想与其他活动通信,则应使用 Intent 来执行此操作。

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

在 android 中,不可能创建另一个活动的对象。

于 2012-06-10T11:54:12.663 回答
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;
            }
        }

    }

}
于 2012-06-10T11:56:00.920 回答