0

我正在制作一个应用程序,它将上传从 android 手机拍摄的图像。在我当前的代码中,我的 if 条件之一变为 true,即返回 0,因此我的函数停止工作,并且它也不会将图像上传到服务器。

这是我的代码

public class Camera extends Activity {
ImageView ivUserImage;
Button bUpload;
Intent i;
int CameraResult = 0;
Bitmap bmp;

int serverResponseCode = 0;
ProgressDialog dialog = null;

@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) {
                dialog = ProgressDialog.show(Camera.this, "", "Uploading file...", true);
                 new Thread(new Runnable() {
                        public void run() {
                             runOnUiThread(new Runnable() {
                                public void run() {
                                    //tv.setText("uploading started.....");
                                    Toast.makeText(getBaseContext(), "File is uploading...", Toast.LENGTH_LONG).show();
                                }
                             });
                         int response= uploadFile(bmp.toString());
                         //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;
    //Toast.makeText(getApplicationContext(), sourceFileUri, Toast.LENGTH_LONG).show();
    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(Camera.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(Camera.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(Camera.this, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
        Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
    }

    dialog.dismiss();
    return serverResponseCode;
}

}

在我的 uploadFile() 方法中,此条件变为 true if (!sourceFile.isFile()) { Log.e("uploadFile", "Source File Does not exist"); return 0; }

从相机拍摄的上传图像如何解决这个问题?

更新

这是我的日志猫

06-10 16:30:08.595: D/CLIPBOARD(27966): Hide Clipboard dialog at Starting input: finished by someone else... !
06-10 16:30:10.305: D/PhoneWindow(27966): couldn't save which view has focus because the focused view com.android.internal.policy.impl.PhoneWindow$DecorView@4053eca0 has no id.
06-10 16:30:10.980: D/CLIPBOARD(27966): Hide Clipboard dialog at Starting input: finished by someone else... !
06-10 16:30:11.015: W/IInputConnectionWrapper(27966): showStatusIcon on inactive InputConnection
06-10 16:32:18.005: D/PhoneWindow(27966): couldn't save which view has focus because the focused view com.android.internal.policy.impl.PhoneWindow$DecorView@4053eca0 has no id.
06-10 16:32:38.890: D/dalvikvm(27966): GC_EXTERNAL_ALLOC freed 101K, 46% free 3097K/5639K, external 879K/1025K, paused 37ms
06-10 16:37:19.145: D/PhoneWindow(27966): couldn't save which view has focus because the focused view com.android.internal.policy.impl.PhoneWindow$DecorView@4053eca0 has no id.
06-10 16:39:01.805: E/uploadFile(27966): Source File Does not exist
06-10 16:39:01.805: I/System.out(27966): RES : 0
06-10 16:39:09.185: D/PhoneWindow(27966): couldn't save which view has focus because the focused view com.android.internal.policy.impl.PhoneWindow$DecorView@4053eca0 has no id.
06-10 16:39:09.475: D/CLIPBOARD(27966): Hide Clipboard dialog at Starting input: finished by someone else... !
4

2 回答 2

0

您通过此行发送位图字符串

int response=uploadFile(bmp.toString());

在这里您发送位图字符串。不要发送图像的路径。所以这个 (!sourceFile.isFile()) 行没有找到任何文件路径。

我认为这会造成问题。

你调试你的代码,帮助你找到问题。

谢谢

于 2012-06-10T13:19:35.917 回答
0

从相机拍摄的上传图像如何解决这个问题?

关注 Snippet 将对您有所帮助。

public void UploadImage(Bitmap bm) throws Exception {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bm.compress(CompressFormat.JPEG, 75, bos);
            byte[] data = bos.toByteArray();
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost postRequest = new HttpPost(
                    "http://www.example.info/androidfileupload/index.php");
            ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");

            MultipartEntity reqEntity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);
            reqEntity.addPart("uploaded", 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();

            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());
        }
    }
于 2012-06-10T12:53:16.000 回答