Create File from Uri type android

前端 未结 1 646
执笔经年
执笔经年 2020-12-19 12:59

I\'m trying to select image from gallery then convert this image to File and send it via HttpPost but I\'m getting always FileNotFoundException. This my Code :

相关标签:
1条回答
  • 2020-12-19 13:44
     Uri currImageURI = data.getData();
    

    printing currImageURI will give you some thing like this:

    content://media/external/images/media/47
    

    But what we need is the absolute path of that particular image . So we need to get real path from uri

    public String getRealPathFromURI(Context context, Uri contentUri) {
      Cursor cursor = null;
      try { 
        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = context.getContentResolver().query(contentUri,  proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
      } finally {
        if (cursor != null) {
          cursor.close();
        }
      }
    }
    

    Now modifiy your code like

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (resultCode == Activity.RESULT_OK) {
                if (requestCode == 1) {
                    // currImageURI is the global variable I’m using to hold the content:
                    currImageURI = data.getData();
                    //Save the currImageUri (URI type) to global variable.
                    photosHolder.getInstance().setOneIm(getRealPathFromURI(getActivity(),currImageURI));
                }
            }
        }
    
    public String getRealPathFromURI(Context context, Uri contentUri) {
      Cursor cursor = null;
      try { 
        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = context.getContentResolver().query(contentUri,  proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
      } finally {
        if (cursor != null) {
          cursor.close();
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题