Android 10 打开失败:ENOENT没有那个文件或目录

问题描述

我遇到了 pdf 的问题,我想使用 Multipart 上传 pdf,但问题是当我传递文件路径时,android 10 给了我这个错误

关于活动结果:

Uri uri = data.getData();
String src = uri.getPath();
File file = new File(src);
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"),file);
MultipartBody.Part body = MultipartBody.Part.createFormData("userfile",file.getName(),requestBody);

解决方法

context.contentResolver.openInputStream(uri).?use{
      // read bytes and create requestbody here
}

不要在 api 29 及以上版本上使用 RequestBody.create(MediaType.parse("/"),file) ,因为它会尝试打开 inputteam 并抛出异常。(如果启用范围存储并且文件不是来自媒体)使用字节数组。