Java 上传安卓手机拍摄的图像

Java 上传安卓手机拍摄的图像,java,android,Java,Android,我正在制作一个应用程序,可以上传从安卓手机拍摄的图片。在我当前的代码中,我的一个if条件变为true,返回0,因此我的函数停止工作,它也不会将图像上载到服务器 这是我的密码 public class Camera extends Activity { ImageView ivUserImage; Button bUpload; Intent i; int CameraResult = 0; Bitmap bmp; int serverResponseCode = 0; ProgressDial

我正在制作一个应用程序,可以上传从安卓手机拍摄的图片。在我当前的代码中,我的一个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()方法中,如果(!sourceFile.isFile()),则此条件变为true
{
Log.e(“上传文件”,“源文件不存在”);
返回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... !
我如何解决这个问题上传的图像是从 照相机

下面的代码片段将对您有所帮助

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

通过此行发送位图字符串

int response=uploadFile(bmp.toString())

在这里您发送位图字符串。不要发送图像的路径。因此,此(!sourceFile.isFile())行未找到任何文件路径

我认为这是个问题

您可以调试代码来帮助您发现问题


谢谢

调试后我得到了这个android.graphics。Bitmap@4058a368在SourceFileUri中,它不是文件url。若你们想检查文件是否存在,那个么你们需要在拍照后将其保存在手机存储器或SD卡中。最好上传照片而不保存。是的,这正是我想要的。如何上传图像而不保存到手机?我将非常感谢您提供的任何代码示例。