java 从 Uri 类型 android 创建文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27103529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:13:39  来源:igfitidea点击:

Create File from Uri type android

javaandroidfileuriloopj

提问by Chlebta

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 :

我正在尝试从图库中选择图像,然后将此图像转换为 File 并通过 HttpPost 发送,但我总是收到FileNotFoundException. 这是我的代码:

Selecting the photo

选择照片

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

Converting the photo

转换照片

                // First Try
                File myFile = new File((photosHolder.getInstance().getOneIm()).toString());
                params.put("visit_report[photos_attributes][0][file]",myFile); **The exception Raised here
// second try 
                File myFile2 = new File((photosHolder.getInstance().getOneIm()).getPath());
                params.put("visit_report[photos_attributes][1][file]",myFile2); ** Also here

And those are myFiles Value while debuging :

这些是调试时的 myFiles 值:

mFile : content:/com.android.providers.media.documents/document/image%3A19143
myFile2 : /document/image:19143

So any help ?

那么有什么帮助吗?



UpdateI have tried this solution also :

更新我也试过这个解决方案:

//get The real path from uri then save it (and then use it to create the file)
photosHolder.getInstance().setUriString(getRealPathFromURI(currImageURI));

//Convert the image URI to the direct file system path of the image file
    private String getRealPathFromURI(Uri contentURI) {
        String result = "";
        try {
        Cursor cursor = getActivity().getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) { // Source is Dropbox or other similar local file path
            result = contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
            result = cursor.getString(idx); // Exception raised HERE
            cursor.close(); }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

But I got java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from itand the idxvar == to -1

但我得到java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from itidxvar == 到-1

Also I have tried @Praneeth Kalluri Solution but it returns always null as result.

我也试过@Praneeth Kalluri 解决方案,但结果总是返回 null。

回答by Praneeth Kalluri

 Uri currImageURI = data.getData();

printing currImageURI will give you some thing like this:

打印 currImageURI 会给你一些这样的东西:

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

但是我们需要的是那个特定图像的绝对路径。所以我们需要从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();
    }
  }
}