首页 > 解决方案 > 如何使用 okhttp 和内容 URI 在 Android 11 中将文件上传到服务器?(PDF,docx..)

问题描述

我正在使用 android 中的 okhttp 库将文件上传到服务器。我曾经从存储访问框架返回的 URI 中获取文件的真实路径,然后将其上传。

在 android 11 中,我可以获得媒体文件的真实路径,但对于非媒体文件,如文档“content://com.android.providers.media.documents/document/document XX ”,我得到一个空路径。“content://com.android.providers.media.documents/document/ image XX”将通过返回 /storage/emulated/0/Download/xxx.jpeg 正常工作

有人可以为我提供在 android 11 中获取文档真实路径的方法吗?或者如果有另一种上传文件的方式而不需要获取真实路径。

谢谢,

        String path = FileUtils.getPath(this, uri);//Get the absolute path of the file through uri
  
        File file = new File(path);//Create a specific file class
        String fileName = file.getName();//To get the file name is mainly the suffix of the file name

        String type = getContentResolver().getType(uri);
        RequestBody requestBody = RequestBody.create(file, MediaType.parse(type));
        ...

标签: androidfile-uploadokhttpandroid-11scoped-storage

解决方案


推荐阅读