简体   繁体   English

从 URI 获取路径抛出异常

[英]Get path from URI throws exception

I have an Android application that i'm working on and now i'm trying to get a File from an URI (i'll use an intent to get an image from gallery and then upload it to a node.js server using Ion).我有一个正在开发的 Android 应用程序,现在我正在尝试从 URI 获取文件(我将使用意图从图库中获取图像,然后使用 Ion 将其上传到 node.js 服务器) . Te problem is it always throws an exception.问题是它总是抛出异常。 I tried debugging and got the Uri.toString().我尝试调试并得到了 Uri.toString()。 It looks something kind of like this:它看起来像这样:

content://com.android.providers.media.documents/document/image%3A102

I know for a fact that it should look like this:我知道它应该是这样的:

content://com.android.providers.media.documents/document/image:102

I know that the %3A is a representation of :, but why does it appear in the Uri and, how can i fix it?我知道 %3A 是 : 的表示,但为什么它会出现在 Uri 中,我该如何修复它? Finally, how can i get my file from this Uri?最后,我怎样才能从这个 Uri 中获取我的文件?

i'm trying to get a File from an URI我正在尝试从 URI 中获取文件

A Uri is not a file. Uri不是文件。 A Uri does not have to point to anything on the filesystem, let alone a place that you can access. Uri不必指向文件系统上的任何内容,更不用说您可以访问的地方了。

but why does it appear in the Uri但为什么它会出现在 Uri 中

A Uri is an opaque handle. Uri是一个不透明的句柄。 It can be whatever the ContentProvider wants it to be.它可以是ContentProvider想要的任何东西。

how can i fix it?我该如何解决?

You don't, any more than you "fix" https://stackoverflow.com/questions/41795342/get-path-from-uri-throws-exception because you do not like eight-digit numbers starting with 4 .你不会,就像你“修复” https://stackoverflow.com/questions/41795342/get-path-from-uri-throws-exception因为你不喜欢以4开头的八位数字。 Just as the Stack Overflow Web server defines that URLs it uses, so does a ContentProvider define what Uri values it uses.正如 Stack Overflow Web 服务器定义它使用的 URL 一样, ContentProvider定义它使用的Uri值。

Finally, how can i get my file from this Uri?最后,我怎样才能从这个 Uri 中获取我的文件?

Ideally, you don't.理想情况下,你不会。 You use ContentResolver and openInputStream() to get an InputStream on the content identified by that Uri , and Ion uses that.您使用ContentResolveropenInputStream()在该Uri标识的内容上获取InputStream ,Ion 使用它。

If Ion does not support this and can only work with a file, use the InputStream to copy the bytes to some FileOutputStream that you control (eg, in getCacheDir() ).如果 Ion 不支持此功能并且只能处理文件,请使用InputStream将字节复制到您控制的某个FileOutputStream (例如,在getCacheDir() )。 Use that file for your upload, then delete the file when you are done.使用该文件进行上传,然后在完成后删除该文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM