Request write permission for SD Card - android

I am trying to write data to the SD card for android using the permission_handler package but it seems that PermissionGroup.storage only request permission for internal storage. Is what I'm trying to do possible?
This is the my code for requesting permission:
Future<bool> _checkPermission() async {
PermissionStatus permission = await Permission.storage.status;
print(permission);
if (permission != PermissionStatus.granted) {
if (await Permission.storage.request().isGranted) {
return true;
}
} else {
return true;
}
return false;
}
And this is the error I get when I try to create a folder on the sd card.
PS: This works for internal storage
Unhandled Exception: FileSystemException: Creation failed, path = '/storage/1EFF-130C/Music/2020' (OS Error: Permission denied, errno = 13)

Micro SD cards are read only on modern Android devices.
Only one app specific directory is writable.
On Android Q+ the card is not even readable except for that directory.
You can however use SAF for full access.

Related

OS Error: Operation not permitted, errno = 1) even with MANAGE_EXTERNAL_STORAGE

I have an application that generates some PDFs and CSV files and at the moment I am saving these files into the files folder in the application directory of the Android phone. Then the user needs to manually move the files to another folder (for example Documents or Downloads).
I would like to save the file to the Documents or Download folder (one of the two, is the same) automatically at runtime, after the files are generated by the app. The target devices has Android 11 so I have any kind of problems with managing the external storage.
Android Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.example">
<!-- PERMISSIONS -->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
...
...
Permissions requested at startup:
requestPermissions() async {
try {
await [
Permission.storage,
Permission.manageExternalStorage,
].request();
} catch (e) {
LoggerService().error("PERMISSIONS REQUEST ERROR", e.toString());
}
}
Method that saves the files:
Future<String> export(Uint8List pdf, {String? fileName}) async {
Directory dir = Directory(EnvironmentService.documentsPath);
String path = "${dir.path}/${fileName ?? "${uuid.v4()}.pdf"}";
File file = File(path);
await file.writeAsBytes(pdf);
return path;
}
Path where I am trying to save the files:
static const String documentsPath = "/storage/emulated/0/Documents";
When saving the file I always get OS Error: Operation not permitted, errno = 1) error, even if I have granted the MANAGE_EXTERNAL_STORAGE permission. The application will not be published on the Play Store, and needs to be working only on Android.
Any idea of what's happening?

adding lines to your AndroidManifest.xml file - fail to provide permission

I already placed the permission to allow external storage of document and potentially list all PDF documents. Despite adding the lines to your AndroidManifest.xml file, the error message keeps appearing when widget is launched.
Please advise how to fix this error message.
Exception has occurred.
FileManagerError (
Try to add thes lines to your AndroidManifest.xml file
`<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>`
`<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>`
and grant storage permissions to your applicaion from app settings
FileSystemException: Directory listing failed, path = '/storage/emulated/0/' (OS Error: Permission denied, errno = 13))
This is the method where the error comes from:
void getFiles() async { //asyn function to get list of files
List<StorageInfo> storageInfo = await PathProviderEx.getStorageInfo();
var root = storageInfo[0].rootDir; //storageInfo[1] for SD card, geting the root directory
var fm = FileManager(root: Directory(root)); //
files = await fm.filesTree(
excludedPaths: ["/storage/emulated/0/Android"],
extensions: ["pdf"] //optional, to filter files, list only pdf files
);
setState(() {}); //update the UI
}
After adding the following permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Add the following package to the pubspec.yaml file:
https://github.com/Baseflow/flutter-permission-handler
dependencies:
permission_handler: ^5.0.1+1
Then you can request storage permission:
if (await Permission.storage.request().isGranted) {
// Either the permission was already granted before or the user just granted it.
}

Ionic - EACCES (Permission denied) error when uploading video

I'm having some difficulties trying upload video file to server using Cordova Camera Plugin and cordova-plugin-advanced-http. The code works like a charm when uploading an image from gallery, but no matter what I do, I always receive EACCES (Permission denied) when uploading a video from gallery:
file url -> file:///storage/emulated/0/DCIM/Camera/VID_20200908_114957.mp4
post-post-module-es2015.js:240 {status: -1, error: "There was an error with the request: /storage/emulated/0/DCIM/Camera/VID_20200908_114957.mp4: open failed: EACCES (Permission denied)"
Looking only at the error message, we can conclude it's a permission issue, so I tried use cordova-plugin-android-permissions and request READ_EXTERNAL_STORAGE permission. No success, the app has the permission but the error remains the same.
This is part of the code used to upload
private chooseContentUsingCameraPlugin(SOURCE: number) {
const options: CameraOptions = {
destinationType: this.camera.DestinationType.FILE_URI,
mediaType: this.camera.MediaType.ALLMEDIA,
sourceType: SOURCE
};
this.camera.getPicture(options).then((contentUrl: string) => {
if (contentUrl.indexOf('://') === -1)
contentUrl = 'file://' + contentUrl;
const queryIndex = contentUrl.lastIndexOf('?');
if (queryIndex !== -1)
contentUrl = contentUrl.substring(0, queryIndex);
console.log('file url -> ', contentUrl);
this.startUpload(contentUrl);
}, (err) => this.onUploadError(err));
}
private startUpload(fileUrl){
...
this.nativeHttp.uploadFile(req.url, null, headers, fileUrl, fileName).then(res => {
let data = res.data;
if (res.data && (req.responseType === undefined || req.responseType === 'json'))
data = JSON.parse(res.data);
console.log(data)
}).catch(error => {
console.log(error)
});
}
can someone explain what could be causing this issue?
It's possible that the file you're trying to upload is not in the scope of your permission. This is what the documentation says:
This is a soft restricted permission which cannot be held by an app it its full form until the installer on record whitelists the permission. Specifically, if the permission is whitelisted the holder app can access external storage and the visual and aural media collections while if the permission is not whitelisted the holder app can only access to the visual and aural medial collections. Also the permission is immutably restricted meaning that the whitelist state can be specified only at install time and cannot change until the app is installed. For more details see PackageInstaller.SessionParams.setWhitelistedRestrictedPermissions(Set).

How to have the necessary permission to Write File in Removal External Storage in Android without resorting to Root

I'm using Samsung J7 Unrooted for Testing,
My AndroidManifest.xml contains the necessary permissions to write to external storage
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
I don't encounter any error when I used the code:
File myFile = new File("sdcard/Billing/mysdfile.txt");
It save the file on the Device Storage.
But when I specify the removable SDCard using the code:
File myFile = new File("/storage/extSdCard/mysdfile.txt");
I encounter the error :
open failed: EACCES (Permission denied)
I've tried different ways to point to the removable SDCard but encountered the same "open failed: EACCES (Permission denied)" error.
I've checked if I have the necessary permissions to write to external storages and it always say "Granted"
public void verifyStoragePermissions() {
if (ContextCompat.checkSelfPermission(InitActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getBaseContext(), "Denied", Toast.LENGTH_SHORT).show();
if (ActivityCompat.shouldShowRequestPermissionRationale(InitActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
} else {
}
}else{
Toast.makeText(getBaseContext(), "Granted",Toast.LENGTH_SHORT).show();
}
}
I've tried almost everything suggested listed in the google search but to no avail. There are a Few who advises to "Root" the phone but that is unfortunately not an option for me...
Hope someone can help me gain the needed permission rights to save files in my removable external storage without resorting to "Rooting" the phone.

fopen failed while writing into an external SDcard in Android native code

When I am trying to write into external SDcard from android native code, I am getting permission denied in fopen.
mFp = fopen("/storage/extSdCard/Output/test.txt", "wb");
if I print strerror(errno) it gives ->
fopen(/storage/extSdCard/Output/test.txt) failed: Permission denied
Please note that I have also given the permissions in my Application manifest :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
....
</manifest>
and also :
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
is returing true.
Please check if the external storage is an external card that is inserted or the sdcard that comes with the device.If it is an sdcard that comes with the device itself try your path as "/mnt/drive_path" and check if you native method is able to write to your storage.

Categories

Resources