简体   繁体   English

FileNotFoundException open failed: EPERM (Operation not allowed) during save image file to internal storage on android

[英]FileNotFoundException open failed: EPERM (Operation not permitted) during saving image file to internal storage on android

I faced this problem when I tried to save the image to internal storage on android.当我尝试将图像保存到 android 上的内部存储时,我遇到了这个问题。

public static String setImage(Bitmap image) {
    if (image != null) {
        FileOutputStream outputStream = null;
        File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Caramel");
        dir.mkdir();
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(dir, fileName);
        try {
            outputStream = new FileOutputStream(file);
            image.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            outputStream.flush();
            outputStream.close();
            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

All goes nice and well, and I can see my Bitmap image in debug mode, but all the same, i get the next error:一切顺利,我可以在调试模式下看到我的 Bitmap 映像,但都一样,我得到下一个错误:

W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Caramel/1587724428205.jpg: open failed: EPERM (Operation not permitted)
    W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:495)
    W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:235)
    W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:186)
    W/System.err:     at com.example.caramel.Position.setImage(Position.java:176)
    W/System.err:     at com.example.caramel.PositionActivity.onActivityResult(PositionActivity.java:129)
    W/System.err:     at android.app.Activity.dispatchActivityResult(Activity.java:8300)
    W/System.err:     at android.app.ActivityThread.deliverResults(ActivityThread.java:4905)
    W/System.err:     at android.app.ActivityThread.handleSendResult(ActivityThread.java:4953)
    W/System.err:     at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
    W/System.err:     at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    W/System.err:     at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2043)
    W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:106)
    W/System.err:     at android.os.Looper.loop(Looper.java:216)
    W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:7464)
    W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
    W/System.err:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
    W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:955)
    W/System.err: Caused by: android.system.ErrnoException: open failed: EPERM (Operation not permitted)
    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:7360)
    W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:481)
    W/System.err:   ... 17 more

It seems, that reason could be in my Manifest.xml file, but i've already set these permissions:看来,这个原因可能在我的 Manifest.xml 文件中,但我已经设置了这些权限:

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

Thanks for your support, guys.谢谢你们的支持,伙计们。

I faced this problem when i tried to save image to internal storage on android.当我尝试将图像保存到 android 上的内部存储时,我遇到了这个问题。

public static String setImage(Bitmap image) {
    if (image != null) {
        FileOutputStream outputStream = null;
        File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Caramel");
        dir.mkdir();
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(dir, fileName);
        try {
            outputStream = new FileOutputStream(file);
            image.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            outputStream.flush();
            outputStream.close();
            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

All goes nice and well, and i can see my Bitmap image in debug mode, but all the same i get next error:一切顺利,我可以在调试模式下看到我的 Bitmap 映像,但同样我得到下一个错误:

    W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Caramel/1587724428205.jpg: open failed: EPERM (Operation not permitted)
W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:495)
W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:235)
W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:186)
W/System.err:     at com.example.caramel.Position.setImage(Position.java:176)
W/System.err:     at com.example.caramel.PositionActivity.onActivityResult(PositionActivity.java:129)
W/System.err:     at android.app.Activity.dispatchActivityResult(Activity.java:8300)
W/System.err:     at android.app.ActivityThread.deliverResults(ActivityThread.java:4905)
W/System.err:     at android.app.ActivityThread.handleSendResult(ActivityThread.java:4953)
W/System.err:     at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
W/System.err:     at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
W/System.err:     at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2043)
W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:106)
W/System.err:     at android.os.Looper.loop(Looper.java:216)
W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:7464)
W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
W/System.err:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:955)
W/System.err: Caused by: android.system.ErrnoException: open failed: EPERM (Operation not permitted)
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:7360)
W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:481)
W/System.err:   ... 17 more

It seems, that reason could be in my Manifest.xml file, but i've already set these permissions:看来,这个原因可能在我的 Manifest.xml 文件中,但我已经设置了这些权限:

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

Thanks for your support, guys.谢谢你们的支持,伙计们。

I faced this problem when i tried to save image to internal storage on android.当我尝试将图像保存到 android 上的内部存储时,我遇到了这个问题。

public static String setImage(Bitmap image) {
    if (image != null) {
        FileOutputStream outputStream = null;
        File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Caramel");
        dir.mkdir();
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(dir, fileName);
        try {
            outputStream = new FileOutputStream(file);
            image.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            outputStream.flush();
            outputStream.close();
            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

All goes nice and well, and i can see my Bitmap image in debug mode, but all the same i get next error:一切顺利,我可以在调试模式下看到我的 Bitmap 映像,但同样我得到下一个错误:

    W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Caramel/1587724428205.jpg: open failed: EPERM (Operation not permitted)
W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:495)
W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:235)
W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:186)
W/System.err:     at com.example.caramel.Position.setImage(Position.java:176)
W/System.err:     at com.example.caramel.PositionActivity.onActivityResult(PositionActivity.java:129)
W/System.err:     at android.app.Activity.dispatchActivityResult(Activity.java:8300)
W/System.err:     at android.app.ActivityThread.deliverResults(ActivityThread.java:4905)
W/System.err:     at android.app.ActivityThread.handleSendResult(ActivityThread.java:4953)
W/System.err:     at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
W/System.err:     at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
W/System.err:     at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2043)
W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:106)
W/System.err:     at android.os.Looper.loop(Looper.java:216)
W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:7464)
W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
W/System.err:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:955)
W/System.err: Caused by: android.system.ErrnoException: open failed: EPERM (Operation not permitted)
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:7360)
W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:481)
W/System.err:   ... 17 more

It seems, that reason could be in my Manifest.xml file, but i've already set these permissions:看来,这个原因可能在我的 Manifest.xml 文件中,但我已经设置了这些权限:

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

Thanks for your support, guys.谢谢你们的支持,伙计们。

I got the issue In android 11 ":" is not allowed in file name.我在 android 11 中遇到问题:文件名中不允许出现“:”。 And when you append date at the end of file name its add ":" at the end.当您在文件名末尾添加 append 日期时,在末尾添加“:”。 so just replace all ":" with "."所以只需将所有“:”替换为“。” and its working fine.并且工作正常。

        String fileName = 
              System.currentTimeMillis().toString().replaceAll(":", ".") + ".jpg";

I faced this problem when i tried to save image to internal storage on android.当我尝试将图像保存到 android 上的内部存储时,我遇到了这个问题。

public static String setImage(Bitmap image) {
    if (image != null) {
        FileOutputStream outputStream = null;
        File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Caramel");
        dir.mkdir();
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(dir, fileName);
        try {
            outputStream = new FileOutputStream(file);
            image.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            outputStream.flush();
            outputStream.close();
            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

All goes nice and well, and i can see my Bitmap image in debug mode, but all the same i get next error:一切顺利,我可以在调试模式下看到我的 Bitmap 映像,但同样我得到下一个错误:

    W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Caramel/1587724428205.jpg: open failed: EPERM (Operation not permitted)
W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:495)
W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:235)
W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:186)
W/System.err:     at com.example.caramel.Position.setImage(Position.java:176)
W/System.err:     at com.example.caramel.PositionActivity.onActivityResult(PositionActivity.java:129)
W/System.err:     at android.app.Activity.dispatchActivityResult(Activity.java:8300)
W/System.err:     at android.app.ActivityThread.deliverResults(ActivityThread.java:4905)
W/System.err:     at android.app.ActivityThread.handleSendResult(ActivityThread.java:4953)
W/System.err:     at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
W/System.err:     at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
W/System.err:     at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2043)
W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:106)
W/System.err:     at android.os.Looper.loop(Looper.java:216)
W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:7464)
W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
W/System.err:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:955)
W/System.err: Caused by: android.system.ErrnoException: open failed: EPERM (Operation not permitted)
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:7360)
W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:481)
W/System.err:   ... 17 more

It seems, that reason could be in my Manifest.xml file, but i've already set these permissions:看来,这个原因可能在我的 Manifest.xml 文件中,但我已经设置了这些权限:

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

Thanks for your support, guys.谢谢你们的支持,伙计们。

I faced this problem when i tried to save image to internal storage on android.当我尝试将图像保存到 android 上的内部存储时,我遇到了这个问题。

public static String setImage(Bitmap image) {
    if (image != null) {
        FileOutputStream outputStream = null;
        File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Caramel");
        dir.mkdir();
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(dir, fileName);
        try {
            outputStream = new FileOutputStream(file);
            image.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            outputStream.flush();
            outputStream.close();
            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

All goes nice and well, and i can see my Bitmap image in debug mode, but all the same i get next error:一切顺利,我可以在调试模式下看到我的 Bitmap 映像,但同样我得到下一个错误:

    W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Caramel/1587724428205.jpg: open failed: EPERM (Operation not permitted)
W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:495)
W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:235)
W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:186)
W/System.err:     at com.example.caramel.Position.setImage(Position.java:176)
W/System.err:     at com.example.caramel.PositionActivity.onActivityResult(PositionActivity.java:129)
W/System.err:     at android.app.Activity.dispatchActivityResult(Activity.java:8300)
W/System.err:     at android.app.ActivityThread.deliverResults(ActivityThread.java:4905)
W/System.err:     at android.app.ActivityThread.handleSendResult(ActivityThread.java:4953)
W/System.err:     at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
W/System.err:     at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
W/System.err:     at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2043)
W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:106)
W/System.err:     at android.os.Looper.loop(Looper.java:216)
W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:7464)
W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
W/System.err:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:955)
W/System.err: Caused by: android.system.ErrnoException: open failed: EPERM (Operation not permitted)
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:7360)
W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:481)
W/System.err:   ... 17 more

It seems, that reason could be in my Manifest.xml file, but i've already set these permissions:看来,这个原因可能在我的 Manifest.xml 文件中,但我已经设置了这些权限:

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

Thanks for your support, guys.谢谢你们的支持,伙计们。

In android 11 you can use this pattern在 android 11 中,您可以使用此模式

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1) {
    mPath= getActivity().getExternalFilesDir(Environment.DIRECTORY_DCIM) + "/" + now + ".jpeg";
}
else
{
    mPath= Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpeg";
}

You can save photos in DCIM or create a directory in it in Android 11, which is a good pattern.您可以将照片保存在 DCIM 中,或者在 Android 11 中在其中创建目录,这是一个很好的模式。 I'm having the same problem, however after I do this, everything works fine.我遇到了同样的问题,但是在我这样做之后,一切正常。

   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1) {
    Yourpath= getActivity().getExternalFilesDir
    (Environment.DIRECTORY_DCIM) + "/" + nameoffile + ".jpeg";
      }
    else
       {
     
       Yourpath=Environment.getExternalStorageDirectory()
      .toString() + "/" + nameoffile + ".jpeg";
       }

Happy Coding!快乐编码!

you need to grant permission on the Android emulator:您需要授予 Android 仿真器的权限:

  • touch your app in Android Emulator 2 seconds,在 Android Emulator 中触摸您的应用 2 秒,
  • go to app info. go 到应用信息。

Android 模拟器上的应用信息

  • go to permissions. go 权限。
  • select Files and media select 文件和媒体
  • Allow management files.允许管理文件。

in my case就我而言

just you need -> Allow management files.只是你需要-> 允许管理文件。 go to setting and allow it. go 设置并允许它。


and also check other require run time permissions.并检查其他需要运行时权限。

Starting with SDK version 30, you can NOT extend android:requestLegacyExternalStorage="true" .从 SDK 版本 30 开始,您不能扩展android:requestLegacyExternalStorage="true" Instead modify you ImageLoader library a little.而是稍微修改一下 ImageLoader 库。 I see you have to modify you file path: File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Caramel");我看到你必须修改你的文件路径: File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Caramel"); into something like File dir = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "Caramel");进入类似File dir = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "Caramel"); . . This should do a trick.这应该可以解决问题。

This worked for me: MANAGE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE这对我有用: MANAGE_EXTERNAL_STORAGE、READ_EXTERNAL_STORAGE、WRITE_EXTERNAL_STORAGE

in file pubspec.yaml在文件pubspec.yaml

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.4
  permission_handler: ^9.0.2
  flutter_downloader: ^1.5.2
  path_provider: ^2.0.9
  external_path: ^1.0.1

in file AndroidManifest.xml在文件AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<application
        android:label="ejemplo_test"
        android:usesCleartextTraffic="true"
        android:icon="@mipmap/ic_launcher"
        android:requestLegacyExternalStorage="true">
<provider
           android:name="vn.hunghd.flutterdownloader.DownloadedFileProvider"
           android:authorities="${applicationId}.flutter_downloader.provider"
           android:exported="false"
           android:grantUriPermissions="true">
           <meta-data
               android:name="android.support.FILE_PROVIDER_PATHS"
               android:resource="@xml/provider_paths"/>
       </provider>

in file main.dart在文件main.dart

    void main() async{
      WidgetsFlutterBinding.ensureInitialized();
      await FlutterDownloader.initialize(
          debug: true
      );
      runApp(const MyApp());
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      String localPath = "";
      int progress = 0;
      ReceivePort _port = ReceivePort();
    
    @override
      void initState(){
        super.initState();
        initPlatformState();
        IsolateNameServer.registerPortWithName(_port.sendPort, 'downloader_send_port');
        _port.listen((dynamic data) {
          String id = data[0];
          DownloadTaskStatus status = data[1];
          int progress = data[2];
          setState((){ });
        });
        FlutterDownloader.registerCallback(downloadCallback);
        _requestPermissions();
      }

@override
  void dispose() {
    IsolateNameServer.removePortNameMapping('downloader_send_port');
    super.dispose();
  }

  static void downloadCallback(String id, DownloadTaskStatus status, int progress) {
    final SendPort? send = IsolateNameServer.lookupPortByName('downloader_send_port');
    send?.send([id, status, progress]);
  }

Future<void> initPlatformState() async {
    final path = await ExternalPath.getExternalStorageDirectories();
    setState(() {
      localPath = path[0].toString()+"/Android/media/NameAPP";
    });
    log("path: ${localPath}");
    final savedDir = Directory(localPath);
    bool hasExisted = await savedDir.exists();
    if (!hasExisted) {
      savedDir.create(recursive: true);
    }
  }

SaveImages(String url,String name) async{
    log("url: ${url}");
    log("name: ${name}");
    final id = await FlutterDownloader.enqueue(
      url:"${url}",
      savedDir: localPath,
      fileName: name.toString(),
      showNotification: true,
      openFileFromNotification: true,
    );
  }

Future<void> _requestPermissions() async {
    Map<Permission, PermissionStatus> statuses = await [
      Permission.storage,
      Permission.manageExternalStorage
    ].request();
    log("statuses: ${statuses}");
    if (statuses == PermissionStatus.granted) {
      //createFolder("TiendaOnline");
      MensajeToast("Permission granted.",Colors.green);
    } else if (statuses == PermissionStatus.denied) {
      MensajeToast("Denied. Show a dialog with a reason and again ask for the permission.",Colors.red);
    } else if (statuses == PermissionStatus.permanentlyDenied) {
      MensajeToast("Take the user to the settings page.",Colors.red);
    }
  }
    
    }

Apparently if you're trying to save to the internal storage for Android 11, you can NOT save in /storage/emulated/0.显然,如果您尝试将 Android 11 保存到内部存储中,则不能保存在 /storage/emulated/0 中。 Only in public folders like Download, Document, etc. This was the case for me, at least.仅在下载、文档等公共文件夹中。至少对我来说是这样。

For me, changing both the compileSdkVersion and the targetSdkVersion to 30 solved the problem.对我来说,将compileSdkVersiontargetSdkVersion都更改为30解决了这个问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 java.io.FileNotFoundException 打开失败:EPERM(不允许操作) - java.io.FileNotFoundException open failed: EPERM (Operation not permitted) MediaRecorder prepare() failed /storage/emulated/0/: open failed: EPERM (Operation not allowed) - MediaRecorder prepare() failed /storage/emulated/0/: open failed: EPERM (Operation not permitted) Android java.io.FileNotFoundException图像打开失败:内部存储中的ENOENT - Android java.io.FileNotFoundException image open failed: ENOENT from internal storage 无法在 macOS 上打开文件 - FileNotFoundException,不允许操作 - Can't open file on macOS - FileNotFoundException, Operation not permitted Android Java 抛出 java.net.SocketException:套接字失败:EPERM(不允许操作) - Android Java throws java.net.SocketException: socket failed: EPERM (Operation not permitted) 尝试将文件保存到内部存储时“不允许操作” - "Operation not permitted" when trying to save file to internal storage 在Android的内部存储中保存文件 - Saving a file on internal storage in Android java.net.SocketException:套接字失败:EPERM(不允许操作) - java.net.SocketException: socket failed: EPERM (Operation not permitted) Google Play服务错误:读取失败:EPERM(不允许操作) - Error in Google Play Services: read failed: EPERM (Operation not permitted) Android - java.io.FileNotFoundException: /storage/emulated/0/Notes/File.txt: open failed: ENOENT (No such file or directory) - Android - java.io.FileNotFoundException: /storage/emulated/0/Notes/File.txt: open failed: ENOENT (No such file or directory)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM