How to read a shared file
Opened this issue · 3 comments
Hello,
First of all,thank you for this plugin, works flawlessly. I was just guessing how can I access a file that has been sent to my application. I tried to use the file cordova plugin, trying to open the path that I receive on the intent , but I'm unable to access the contents, probably because lack of permissions. Is there any other way of doing this ?
Thanks in advance
I know this is quite late, but did you manage to find a solution for it? Stuck at this for a couple of days, any help would be appreciated.
I know this is quite late, but did you manage to find a solution for it? Stuck at this for a couple of days, any help would be appreciated.
Nope, I just stopped trying
I am just going to type this out here if anyone is still trying to find a solution. What I've done is absolute jank and I don't understand why it works but it does.
It is clear the Android doesn't let the file be read by any app willy nilly. Which is why I believe only the app to which the data is sent is allowed to read the file, and why data must be read using JS. I maybe wrong, but this is my hypothesis.
When my component is called, I convert the content://
or file://
url to http url
using capacitor's convertFileSrc function. I can now use this url to call the following function -
(A snippet I found here and adapted to work for my code)
convertFileAndSave = async (url: string) => {
let blob = await fetch(url).then((r) => r.blob());
let dataUrl = await new Promise((resolve) => {
let reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.readAsDataURL(blob);
});
// do stuff with dataUrl
}
Now I can use this base64 data to basically 'read' the file and save it elsewhere. Here is what I am doing in my backend with PHP (CI4)
...
$data = $this->request->getPost('dataUrl');
...
// process the encoded data to save it in appropriate place
$pos = strpos($data, ','); // gets the position of the first comma and
$file = substr($data, $pos+1); // removes data uri - 'data:@file/extension;base64,'
$file = str_replace(' ', '+', $file); // PHP has issues, so replacing ' ' with '+'
$data = base64_decode($file);
...
file_put_contents($file_path, $data); // saves the file
...
Again, this isn't really the best solution, but this is how I've been able to get this to work. If anyone else is able to find a better solution, please do let me know.