【问题标题】:get a file path from a Uri从 Uri 获取文件路径
【发布时间】:2017-11-03 15:45:31
【问题描述】:

当我从 WhatsApp 中“分享图片”并与我的应用分享时,我会得到类似这样的 URI:

content://com.whatsapp.provider.media/item/61025 但我无法从 Uri 获取文件路径。

【问题讨论】:

  • 你无法获得文件路径...你需要它做什么?你需要的是InputStream,而不是“文件路径”,对吧?
  • 如果你想获取图片,那么this answer 应该可以帮助你
  • 我要文件路径 l@pskink
  • 无法从 Content Provider 的 uri 中获取文件路径。但是,如果是文件 uri file:/// 或内容 uri content://com.externalstorage.documents/...,则可以从 uri 获取绝对文件路径。正如 pskink 指出的那样,获取一个 InputStream 并使用该 InputStream 创建一个临时文件。
  • @FatihOzcan 是的,使用 contentResolver 我从谷歌照片 URI 获得了文件路径,但它不适用于 WhatsApp 内容提供商

标签: android android-contentprovider


【解决方案1】:

Documentation 之后,我通过以下方式接收图像意图:

void onCreate (Bundle savedInstanceState) {
    ...
    // Get intent, action and MIME type
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    if (Intent.ACTION_SEND.equals(action) && type != null) {
        if (type.startsWith("image/")) {
            handleSendImage(intent); // Handle single image being sent
        }
    } 
}

ContentResolver 在这种情况下不起作用,因为“_data”字段返回 null。所以我找到了另一种从内容 URI 获取文件的方法。

handleSendImage()中你需要打开inputStream,然后将其复制到一个文件中。

void handleSendImage(Intent intent) throws IOException {
    Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
    if (imageUri != null) {
      File file = new File(getCacheDir(), "image");
      InputStream inputStream=getContentResolver().openInputStream(imageUri);
      try {

        OutputStream output = new FileOutputStream(file);
        try {
          byte[] buffer = new byte[4 * 1024]; // or other buffer size
          int read;

          while ((read = inputStream.read(buffer)) != -1) {
            output.write(buffer, 0, read);
          }

          output.flush();
        } finally {
          output.close();
        }
      } finally {
        inputStream.close();
        byte[] bytes =getFileFromPath(file);
        //Upload Bytes.
      }
    }
  }

getFileFromPath() 获取可以上传到服务器的字节。

  public static byte[] getFileFromPath(File file) {
    int size = (int) file.length();
    byte[] bytes = new byte[size];
    try {
      BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
      buf.read(bytes, 0, bytes.length);
      buf.close();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return bytes;
  }

【讨论】:

  • @bhavesh:你试过这个解决方案了吗?
【解决方案2】:

你可以使用

IputStream is = getContentResolver().OpenInputStream("whatsapp Uri");

查看this答案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 2020-12-07
    • 2011-03-25
    • 1970-01-01
    相关资源
    最近更新 更多