I'm trying to retrieve a file (any type) from file manager and encode this file in a Base64 String. I've found a lot of answers involving IMAGES, but I need any type of file. He's what I'm doing.
I'm retrieving a file(any type) from gallery like this
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose file"), GALLERY_REQUEST_CODE);
And in my result
Uri returnUri = intent.getData();
What gives me 'content://com.android.providers.downloads.documents/document/1646'
Then I try
File file = new File( returnUri.getPath() );
So far so good, but then I try to encode the file into a Base64 string:
String str = null;
try {
str = convertFile(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And the convertFile method
public String convertFile(File file)
throws IOException {
byte[] bytes = loadFile(file);
byte[] encoded = Base64.encode(bytes, Base64.DEFAULT);
String encodedString = new String(encoded);
return encodedString;
}
And the loadFile method
private static byte[] loadFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
long length = file.length();
if (length > Integer.MAX_VALUE) {
Log.i("MobileReport","Anexo -> loadfile(): File is too big!");
// File is too large
}
byte[] bytes = new byte[(int)length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
if (offset < bytes.length) {
throw new IOException("It was not possible to read the entire file "+file.getName());
}
is.close();
return bytes;
}
The error is in the first line of 'loadFile' method
InputStream is = new FileInputStream(file);
The app crashes and in the log I got:
java.io.FileNotFoundException: /document/1646: open failed: ENOENT (No such file or directory)
I've declared the READ and WRITE permissions. Could anyone help me with that error? Thank you!
returnUri
is a Uri
. It is not a filesystem path.
In particular, if you examine it, you will find that it is a content://
Uri
. To get an InputStream
for that content, use openInputStream()
on a ContentResolver
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With