从android中的文件路径获取内容uri

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3004713/
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-08-20 08:14:46  来源:igfitidea点击:

Get content uri from file path in android

androidimage

提问by pankajagarwal

I know the absolute path of an image (say for eg, /sdcard/cats.jpg). Is there any way to get the content uri for this file ?

我知道图像的绝对路径(例如,/sdcard/cats.jpg)。有没有办法获取这个文件的内容uri?

Actually in my code, I download an image and save it at a particular location. In order to set the image in an ImageView instance, currently I open the file using the path, get the bytes and create a bitmap and then set the bitmap in the ImageView instance. This is a very slow process, instead if I could get the content uri then I could very easily use the method imageView.setImageUri(uri)

实际上,在我的代码中,我下载了一个图像并将其保存在特定位置。为了在 ImageView 实例中设置图像,目前我使用路径打开文件,获取字节并创建位图,然后在 ImageView 实例中设置位图。这是一个非常缓慢的过程,相反,如果我可以获得内容 uri,那么我可以很容易地使用该方法 imageView.setImageUri(uri)

回答by Francesco Laurita

Try with:

尝试:

ImageView.setImageURI(Uri.fromFile(new File("/sdcard/cats.jpg")));

Or with:

或与:

ImageView.setImageURI(Uri.parse(new File("/sdcard/cats.jpg").toString()));

回答by Jinal Jogiyani

UPDATE

更新

Here it is assumed that your media (Image/Video) is already added to content media provider. If not then you will not able to get the content URL as exact what you want. Instead there will be file Uri.

这里假设您的媒体(图像/视频)已经添加到内容媒体提供商。如果没有,那么您将无法获得您想要的内容 URL。取而代之的是文件 Uri。

I had same question for my file explorer activity. You should know that the contenturi for file only supports mediastore data like image, audio and video. I am giving you the code for getting image content uri from selecting an image from sdcard. Try this code, maybe it will work for you...

我对我的文件浏览器活动有同样的问题。您应该知道 file 的 contenturi 仅支持图像、音频和视频等媒体存储数据。我正在为您提供通过从 sdcard 中选择图像来获取图像内容 uri 的代码。试试这个代码,也许它对你有用......

public static Uri getImageContentUri(Context context, File imageFile) {
  String filePath = imageFile.getAbsolutePath();
  Cursor cursor = context.getContentResolver().query(
      MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
      new String[] { MediaStore.Images.Media._ID },
      MediaStore.Images.Media.DATA + "=? ",
      new String[] { filePath }, null);
  if (cursor != null && cursor.moveToFirst()) {
    int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
    cursor.close();
    return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + id);
  } else {
    if (imageFile.exists()) {
      ContentValues values = new ContentValues();
      values.put(MediaStore.Images.Media.DATA, filePath);
      return context.getContentResolver().insert(
          MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    } else {
      return null;
    }
  }
}

回答by AndroidDebaser

// This code works for images on 2.2, not sure if any other media types

// 此代码适用于 2.2 上的图像,不确定是否还有其他媒体类型

   //Your file path - Example here is "/sdcard/cats.jpg"
   final String filePathThis = imagePaths.get(position).toString();

   MediaScannerConnectionClient mediaScannerClient = new
   MediaScannerConnectionClient() {
    private MediaScannerConnection msc = null;
    {
        msc = new MediaScannerConnection(getApplicationContext(), this);
        msc.connect();
    }

    public void onMediaScannerConnected(){
        msc.scanFile(filePathThis, null);
    }


    public void onScanCompleted(String path, Uri uri) {
        //This is where you get your content uri
            Log.d(TAG, uri.toString());
        msc.disconnect();
    }
   };

回答by Jon O

The accepted solution is probably the best bet for your purposes, but to actually answer the question in the subject line:

接受的解决方案可能是您的最佳选择,但要实际回答主题行中的问题:

In my app, I have to get the path from URIs and get the URI from paths. The former:

在我的应用程序中,我必须从 URI 中获取路径并从路径中获取 URI。前者:

/**
 * Gets the corresponding path to a file from the given content:// URI
 * @param selectedVideoUri The content:// URI to find the file path from
 * @param contentResolver The content resolver to use to perform the query.
 * @return the file path as a string
 */
private String getFilePathFromContentUri(Uri selectedVideoUri,
        ContentResolver contentResolver) {
    String filePath;
    String[] filePathColumn = {MediaColumns.DATA};

    Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);
    cursor.moveToFirst();

    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    filePath = cursor.getString(columnIndex);
    cursor.close();
    return filePath;
}

The latter (which I do for videos, but can also be used for Audio or Files or other types of stored content by substituting MediaStore.Audio (etc) for MediaStore.Video):

后者(我为视频做的,但也可以用于音频或文件或其他类型的存储内容,通过将 MediaStore.Audio(等)替换为 MediaStore.Video):

/**
 * Gets the MediaStore video ID of a given file on external storage
 * @param filePath The path (on external storage) of the file to resolve the ID of
 * @param contentResolver The content resolver to use to perform the query.
 * @return the video ID as a long
 */
private long getVideoIdFromFilePath(String filePath,
        ContentResolver contentResolver) {


    long videoId;
    Log.d(TAG,"Loading file " + filePath);

            // This returns us content://media/external/videos/media (or something like that)
            // I pass in "external" because that's the MediaStore's name for the external
            // storage on my device (the other possibility is "internal")
    Uri videosUri = MediaStore.Video.Media.getContentUri("external");

    Log.d(TAG,"videosUri = " + videosUri.toString());

    String[] projection = {MediaStore.Video.VideoColumns._ID};

    // TODO This will break if we have no matching item in the MediaStore.
    Cursor cursor = contentResolver.query(videosUri, projection, MediaStore.Video.VideoColumns.DATA + " LIKE ?", new String[] { filePath }, null);
    cursor.moveToFirst();

    int columnIndex = cursor.getColumnIndex(projection[0]);
    videoId = cursor.getLong(columnIndex);

    Log.d(TAG,"Video ID is " + videoId);
    cursor.close();
    return videoId;
}

Basically, the DATAcolumn of MediaStore(or whichever sub-section of it you're querying) stores the file path, so you use that info to look it up.

基本上,DATAMediaStore(或您查询的任何子部分)存储文件路径,因此您可以使用该信息进行查找。

回答by Abhishek Meharia

You can use these two ways based on use

您可以根据用途使用这两种方式

Uri uri = Uri.parse("String file location");

Uri uri = Uri.parse("String file location");

or

或者

Uri uri = Uri.fromFile(new File("string file location"));

Uri uri = Uri.fromFile(new File("string file location"));

I have tried both ways and both works.

我已经尝试了两种方法并且都有效。

回答by artenson.art98

Its late, but may help someone in future.

晚了,但将来可能会帮助某人。

To get content URI for a file, you may use the following method:

要获取文件的内容 URI,您可以使用以下方法:

FileProvider.getUriForFile(Context context, String authority, File file)

FileProvider.getUriForFile(Context context, String authority, File file)

It returns the content URI.

它返回内容 URI。

Check this out to learn how to setup a FileProvider

检查这个以了解如何设置 FileProvider

回答by Thracian

Easiest and the robust way for creating Content Uri content://from a File is to use FileProvider. Uri provided by FileProvider can be used also providing Uri for sharing files with other apps too. To get File Uri from a absolute path of Fileyou can use DocumentFile.fromFile(new File(path, name)), it's added in Api 22, and returns null for versions below.

content://从文件创建 Content Uri 的最简单、最可靠的方法是使用FileProvider。FileProvider 提供的 Uri 也可以用于提供 Uri 与其他应用程序共享文件。要从绝对路径获取文件 Uri,File您可以使用 DocumentFile.fromFile(new File(path, name)),它是在 Api 22 中添加的,并且对于以下版本返回 null。

File imagePath = new File(Context.getFilesDir(), "images");
File newFile = new File(imagePath, "default_image.jpg");
Uri contentUri = getUriForFile(getContext(), "com.mydomain.fileprovider", newFile);

回答by BogdanBiv

Obtaining the File ID without writing any code, just with adb shell CLI commands:

无需编写任何代码即可获取文件 ID,只需使用 adb shell CLI 命令:

adb shell content query --uri "content://media/external/video/media" | grep FILE_NAME | grep -Eo " _id=([0-9]+)," | grep -Eo "[0-9]+"

回答by Jorgesys

Is better to use a validation to support versions pre Android N, example:

最好使用验证来支持 Android N 之前的版本,例如:

  if (Build.VERSION.SDK_INT >=  Build.VERSION_CODES.N) {
     imageUri = Uri.parse(filepath);
  } else{
     imageUri = Uri.fromFile(new File(filepath));
  }


  if (Build.VERSION.SDK_INT >=  Build.VERSION_CODES.N) {
     ImageView.setImageURI(Uri.parse(new File("/sdcard/cats.jpg").toString()));         
  } else{
     ImageView.setImageURI(Uri.fromFile(new File("/sdcard/cats.jpg")));
  }

https://es.stackoverflow.com/questions/71443/reporte-crash-android-os-fileuriexposedexception-en-android-n

https://es.stackoverflow.com/questions/71443/reporte-crash-android-os-fileuriexposedexception-en-android-n

回答by caopeng

U can try below code snippet

你可以试试下面的代码片段

    public Uri getUri(ContentResolver cr, String path){
    Uri mediaUri = MediaStore.Files.getContentUri(VOLUME_NAME);
    Cursor ca = cr.query(mediaUri, new String[] { MediaStore.MediaColumns._ID }, MediaStore.MediaColumns.DATA + "=?", new String[] {path}, null);
    if (ca != null && ca.moveToFirst()) {
        int id = ca.getInt(ca.getColumnIndex(MediaStore.MediaColumns._ID));
        ca.close();
        return  MediaStore.Files.getContentUri(VOLUME_NAME,id);
    }
    if(ca != null) {
        ca.close();
    }
    return null;
}