Requiero de poder seleccionar un archivo para poder enviarlo por Retrofit. Pero después de seleccionar el archivo y de poder obtener su información, obtengo el siguiente error al enviarlo con Retrofit:
java.io.FileNotFoundException: /storage/emulated/0/Download/319db0ac0c280ff1cc37aa201a121809.pdf: open failed: EACCES (Permission denied)
Lo extraño es que este código funciona para android 9, 10 y 11, pero falla en el emulador en android 11, 12 y en un dispositivo físico con android 12.
Mi proyecto tiene como objetivo la API 31.
En el manifiesto tengo agregado android:requestLegacyExternalStorage="true"
.
Para abrir la UI del sistema y seleccionar el PDF tengo lo siguiente:
private void doBrowseFile() {
Uri uri = Uri.parse("content://com.android.externalstorage.documents/document/primary:Download");
Intent chooseFileIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
chooseFileIntent.setAction(Intent.ACTION_GET_CONTENT);
chooseFileIntent.addCategory(Intent.CATEGORY_OPENABLE);
chooseFileIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, uri);
chooseFileIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
chooseFileIntent.setType("application/pdf");
chooseFileIntent = Intent.createChooser(chooseFileIntent, getResources().getString(R.string.selec_file));
activityResultPickFile.launch(chooseFileIntent);
}
En attachedFile es donde asigno la referencia del archivo, que posteriormente envío por Retrofit.
ActivityResultLauncher<Intent> activityResultPickFile
= registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == Activity.RESULT_OK) {
Intent data = result.getData();
if (data != null) {
Uri fileUri = data.getData();
String filePath = null;
try {
FileUtils fileUtils = new FileUtils(this.getContext());
filePath = fileUtils.getPath(fileUri);
attachedFile = new File(filePath);
...
}
}
}
});
En ese punto, no consigo problema alguno. Puedo obtener nombre del archivo, tamaño del PDF, y todo funciona bien. Pero al enviarlo por Retrofit, es donde sucede el problema.
val attachFileRequest: MultipartBody.Part = MultipartBody.Part.createFormData(
"file",
attachFile.name,
RequestBody.create(
mimeFile.toMediaTypeOrNull(),
attachFile
)
)
apiService.sendFile(
attachFileRequest
).enqueue(object : Callback<ResponseAPI?> {
override fun onResponse(call: Call<ResponseAPI?>, response: Response<ResponseAPI?>) {
...
}
override fun onFailure(call: Call<ResponseAPI?>, t: Throwable) {
t.printStackTrace()
}
})
Finalmente el error que arroja es el siguiente:
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Download/319db0ac0c280ff1cc37aa201a121809.pdf: open failed: EACCES (Permission denied)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:492)
W/System.err: at java.io.FileInputStream.<init>(FileInputStream.java:160)
W/System.err: at okio.Okio__JvmOkioKt.source(JvmOkio.kt:182)
W/System.err: at okio.Okio.source(Unknown Source:1)
W/System.err: at okhttp3.RequestBody$Companion$asRequestBody$1.writeTo(RequestBody.kt:176)
W/System.err: at okhttp3.MultipartBody.writeOrCountBytes(MultipartBody.kt:157)
W/System.err: at okhttp3.MultipartBody.writeTo(MultipartBody.kt:93)
W/System.err: at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.kt:203)
W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
W/System.err: at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:205)
W/System.err: at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:533)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
W/System.err: at java.lang.Thread.run(Thread.java:923)
W/System.err: Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
W/System.err: at libcore.io.Linux.open(Native Method)
W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:254)
W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
W/System.err: at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7542)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:478)
W/System.err: ... 13 more
Les agradecería cualquier ayudar. Muchas gracias.