Php Android捕获图像并上传,在emulator上显示空路径

Php Android捕获图像并上传,在emulator上显示空路径,php,android,file-upload,Php,Android,File Upload,我有一个应用程序,我需要捕捉相机图像并相应地上传。下面是我的代码。当我尝试从手机上传时,我遇到了问题,无法查看确切的问题是什么,因为我使用了异步任务。所以我在我的模拟器上测试,在那里我可以看到图像,但是当谈到这行Toast.makeText(getApplicationContext(),文件路径是:“+selectedImage,Toast.LENGTH_LONG).show();它在emulator上为路径打印null,但在手机上打印的是精确的路径。如何克服这一点,以便我可以调试它为什么无法

我有一个应用程序,我需要捕捉相机图像并相应地上传。下面是我的代码。当我尝试从手机上传时,我遇到了问题,无法查看确切的问题是什么,因为我使用了异步任务。所以我在我的模拟器上测试,在那里我可以看到图像,但是当谈到这行Toast.makeText(getApplicationContext(),文件路径是:“+selectedImage,Toast.LENGTH_LONG).show();它在emulator上为路径打印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);
        }
    }




}
公共类uploadTask扩展了AsyncTask{
私有进程对话;
私人捕获活动;
私有int id=-1;
私有字符串resultUpload=“”;
公共上载任务(捕获活动,ProgressDialog)
{
这个。活动=活动;
this.progressDialog=progressDialog;
}
@凌驾
受保护的void onPreExecute()
{
progressDialog.show();
}
@凌驾
受保护的整数doInBackground(字符串…arg0)
{
字符串lineEnd=“\r\n”;
字符串双连字符=“--”;
字符串边界=“*******”;
String Tag=“fSnd”;
字符串结果=”;
int-responseCode=0;
尝试
{
Log.e(标记“启动Http文件发送到URL”);
URL connectURL=新URL(“http://*****/upload1.php”);
File sourceFile=新文件(arg0[0]);
字符串iFileName=sourceFile.getName();
if(sourceFile.isFile())
{
//Toast.makeText(getApplicationContext(),“构建流:+selectedImage.toString(),Toast.LENGTH_LONG).show();
FileInputStream FileInputStream=新的FileInputStream(sourceFile);
//Toast.makeText(getApplicationContext(),“文件大小为:”+bytesavable,Toast.LENGTH_LONG).show();
//打开到URL的HTTP连接
HttpURLConnection conn=(HttpURLConnection)connectURL.openConnection();
//允许输入
conn.setDoInput(真);
//允许输出
连接设置输出(真);
//不要使用缓存副本。
conn.SETUSECHACHES(假);
//使用post方法。
conn.setRequestMethod(“POST”);
conn.setRequestProperty(“连接”、“保持活动”);
conn.setRequestProperty(“内容类型”、“多部分/表单数据;边界=“+boundary”);
DataOutputStream dos=新的DataOutputStream(conn.getOutputStream());
写字节(两个连字符+边界+行结束);
writeBytes(“内容处置:表单数据;名称=\“vhlID\”+lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(arg0[1]);
dos.writeBytes(lineEnd);
写字节(两个连字符+边界+行结束);
writeBytes(“内容处置:表单数据;名称=\“sstID\”+lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(arg0[2]);
dos.writeBytes(lineEnd);
写字节(两个连字符+边界+行结束);
writeBytes(“内容处理:表单数据;名称=\”uploadedFile\“文件名=\”+iFileName+“\”+lineEnd);
dos.writeBytes(lineEnd);
Log.e(标记“写入标题”);
//创建最大大小的缓冲区
int bytesavable=fileInputStream.available();
int maxBufferSize=1024;
int bufferSize=Math.min(字节可用,maxBufferSize);
字节[]缓冲区=新字节[bufferSize];
//读取文件并将其写入表单。。。
int bytesRead=fileInputStream.read(buffer,0,bufferSize);
而(字节读取>0)
{
写入(缓冲区,0,缓冲区大小);
bytesAvailable=fileInputStream.available();
bufferSize=Math.min(字节可用,maxBufferSize);
bytesRead=fileInputStream.read(缓冲区,0,缓冲区大小);
}
dos.writeBytes(lineEnd);
写字节(两个连字符+边界+两个连字符+行结束);
//合流
fileInputStream.close();
dos.flush();
Log.e(标记“文件已发送,响应:”+String.valueOf(conn.getResponseCode()));
InputStream is=conn.getInputStream();
//从服务器检索响应
int-ch;
StringBuffer b=新的StringBuffer();
while((ch=is.read())!=-1){b.append((char)ch);}
resultUpload=b.toString();
//Log.i(“响应”,s);
dos.close();
}
}
捕获(例外e){
响应代码=408;
e、 printStackTrace();
}
返回响应代码;
}
@凌驾
受保护的void onPostExecute(整数头代码)
{
progressDialog.disclose();
if(headerCode==200){
activity.showUploadOk(resultUpload);
}      
否则{
activity.showUploadError(resultUpload);
}
}
}

有几件事需要尝试

  • 确保在创建Emulator AVD映像时为SD卡分配了存储空间

  • 尝试自己创建一个文件,然后传入。请参阅有关如何执行此操作的详细信息


是的,我在模拟器上为SD卡分配了2000Mb。我不明白你的第二个建议,你提到尝试自己创建一个文件?除此之外,我实际上在我的手机上再次尝试,我注意到代码工作,但大多数情况下,响应代码是200,但只有很少的时间