Android捕获图像并上传显示模拟器上的空路径

时间:2014-10-09 17:33:28

标签: php android file-upload

我有一个应用程序,我需要拍摄相机图像并相应上传。以下是我的代码。我在手机上尝试上传时出现问题,因为我使用异步任务而无法查看确切的问题。所以我在我的模拟器上测试我可以获得图像,但是当来到这一行Toast.makeText(getApplicationContext(),"文件路径是:" + selectedImage,Toast.LENGTH_LONG).show();它为模拟器上的路径打印null,但在手机上它打印确切的路径。如何克服这个问题,以便我可以说明为什么它无法上传。

public class Capture extends Activity implements OnClickListener {
    private static final int CAMERA_REQUEST = 1888; 
    private ImageView imageView;
    private Button scanBtn1,scanBtn2,submitBtn;
    private TextView vhlTxt,sstTxt;
    private int btnClicked = 0;
    private String selectedImagePath = ""; 

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.capture);
        this.imageView = (ImageView)this.findViewById(R.id.imageView1);
        Button photoButton = (Button) this.findViewById(R.id.button1);
        photoButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
                startActivityForResult(cameraIntent, CAMERA_REQUEST); 
            }
        });

        scanBtn1 = (Button)findViewById(R.id.button2);
        scanBtn2 = (Button)findViewById(R.id.button3);
        scanBtn2 = (Button)findViewById(R.id.btnSubmit);
        vhlTxt = (TextView)findViewById(R.id.editText1);
        sstTxt = (TextView)findViewById(R.id.editText2);
        scanBtn1.setOnClickListener(this);
        scanBtn2.setOnClickListener(this);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        //Toast.makeText(getApplicationContext(), "on activiet result",Toast.LENGTH_LONG).show();
        if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {  
            Bitmap photo = (Bitmap) data.getExtras().get("data"); 
            imageView.setImageBitmap(photo);
            Uri selectedImage = data.getData();
            //String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Toast.makeText(getApplicationContext(), "File Path is :"+selectedImage,Toast.LENGTH_LONG).show();
            try { 
                selectedImagePath = getPath(selectedImage);
                Toast.makeText(getApplicationContext(), "get path :"+selectedImagePath,Toast.LENGTH_LONG).show();

                File sourceFile = new File(selectedImagePath.toString()); 
                if(sourceFile.isFile())
                {
                Toast.makeText(getApplicationContext(), "build stream :"+selectedImage.toString(),Toast.LENGTH_LONG).show();

                FileInputStream fileInputStream = new FileInputStream(sourceFile);
                int bytesAvailable = fileInputStream.available();
                Toast.makeText(getApplicationContext(), "size of file is :"+bytesAvailable,Toast.LENGTH_LONG).show();
                }
                else
                    Toast.makeText(getApplicationContext(), "no source file",Toast.LENGTH_LONG).show();

            } 
            catch (Exception e) {

            }
        }  
        else{
            IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if (scanningResult != null) {
                String scanContent = scanningResult.getContents();
                Toast toast = Toast.makeText(getApplicationContext(), 
                        "Data received!"+scanContent, Toast.LENGTH_LONG);
                    toast.show();
                    if(btnClicked==2)
                        vhlTxt.setText(scanContent); 
                    else if(btnClicked==3)
                        sstTxt.setText(scanContent); 
                }
            else{
                Toast toast = Toast.makeText(getApplicationContext(), 
                    "No scan data received!", Toast.LENGTH_LONG);
                toast.show();
            }
        }
    }

    public void onClick(View v){
        //respond to clicks
        //Toast.makeText(getApplicationContext(), "Done with it",Toast.LENGTH_LONG).show();
        if(v.getId()==R.id.button2){
            btnClicked=2;
            //Toast.makeText(getApplicationContext(), "Done with it",Toast.LENGTH_LONG).show();
            IntentIntegrator scanIntegrator = new IntentIntegrator(this);
            scanIntegrator.initiateScan();

        }
        else if(v.getId()==R.id.button3){
            btnClicked=3;
            //Toast.makeText(getApplicationContext(), "Done with it",Toast.LENGTH_LONG).show();
            IntentIntegrator scanIntegrator = new IntentIntegrator(this);
            scanIntegrator.initiateScan();

        }
        else if(v.getId()==R.id.btnSubmit){

                ProgressDialog progressDialog = new ProgressDialog(Capture.this);
                progressDialog.setMessage("Uploading......");
                progressDialog.setCancelable(false);

                uploadTask ut = new uploadTask(Sealing.this, progressDialog);

                ut.execute(selectedImagePath,vhlTxt.getText().toString(),sstTxt.getText().toString());
          }
    }



    private String getPath(Uri uri) {

        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, projection, null, null,null);

        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();

        return cursor.getString(column_index);
    }
    public void showUploadError(String result)
    {
        Toast.makeText(getApplicationContext(), "upload error :"+result.toString(),Toast.LENGTH_LONG).show();

    }
    public void showUploadOk(String result)
    {
        Toast.makeText(getApplicationContext(), "upload ok :"+result.toString(),Toast.LENGTH_LONG).show();

    }

}

这是我按下提交按钮时调用的上传任务功能。我已经确认我的upload1.php工作正常,因为我已经使用了我的另一个php文件来测试此页面上传并且它有效。任何改进的提示或问题可能在哪里?

public class uploadTask extends AsyncTask<String, Void, Integer> {

    private ProgressDialog progressDialog;
    private Capture activity;
    private int id = -1;
    private String resultUpload = "";

    public uploadTask(Capture activity, ProgressDialog progressDialog)
    {
        this.activity = activity;
        this.progressDialog = progressDialog;
    }

    @Override
    protected void onPreExecute()
    {
        progressDialog.show();
    }

    @Override
    protected Integer doInBackground(String... arg0) 
    {

         String lineEnd = "\r\n";
         String twoHyphens = "--";
         String boundary = "*****";
         String Tag="fSnd";


        String result = "";
        int responseCode = 0;
        try 
        {

            Log.e(Tag,"Starting Http File Sending to URL");
            URL connectURL = new URL("http://*****/upload1.php");
            File sourceFile = new File(arg0[0]);
            String iFileName = sourceFile.getName();

            if(sourceFile.isFile())
            {
            //Toast.makeText(getApplicationContext(), "build stream :"+selectedImage.toString(),Toast.LENGTH_LONG).show();

            FileInputStream fileInputStream = new FileInputStream(sourceFile);

            //Toast.makeText(getApplicationContext(), "size of file is :"+bytesAvailable,Toast.LENGTH_LONG).show();


            // Open a HTTP connection to the URL
            HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();

            // Allow Inputs
            conn.setDoInput(true);

            // Allow Outputs
            conn.setDoOutput(true);

            // Don't use a cached copy.
            conn.setUseCaches(false);

            // Use a post method.
            conn.setRequestMethod("POST");

            conn.setRequestProperty("Connection", "Keep-Alive");

            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"vhlID\""+ lineEnd);
            dos.writeBytes(lineEnd);
            dos.writeBytes(arg0[1]);
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + lineEnd);

            dos.writeBytes("Content-Disposition: form-data; name=\"sstID\""+ lineEnd);
            dos.writeBytes(lineEnd);
            dos.writeBytes(arg0[2]);
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + lineEnd);

            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedFile\";filename=\"" + iFileName +"\"" + lineEnd);
            dos.writeBytes(lineEnd);

            Log.e(Tag,"Headers are written");

            // create a buffer of maximum size
            int bytesAvailable = fileInputStream.available();

            int maxBufferSize = 1024;
            int bufferSize = Math.min(bytesAvailable, maxBufferSize);
            byte[ ] buffer = new byte[bufferSize];

            // read file and write it into form...
            int 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);
            }
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // close streams
            fileInputStream.close();

            dos.flush();

            Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode()));

            InputStream is = conn.getInputStream();

            // retrieve the response from server
            int ch;

            StringBuffer b =new StringBuffer();
            while( ( ch = is.read() ) != -1 ){ b.append( (char)ch ); }
            resultUpload=b.toString();
           // Log.i("Response",s);
            dos.close();
            }

        }
        catch (Exception e) {
            responseCode = 408;
            e.printStackTrace();
        }
        return responseCode;
    }

    @Override
    protected void onPostExecute(Integer headerCode)
    {
        progressDialog.dismiss();


        if(headerCode == 200){

              activity.showUploadOk(resultUpload);
        }      
        else{
              activity.showUploadError(resultUpload);
        }
    }




}

1 个答案:

答案 0 :(得分:0)

要尝试的几件事