首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >扑动Android 11 errno 1

扑动Android 11 errno 1
EN

Stack Overflow用户
提问于 2021-08-30 13:05:51
回答 1查看 172关注 0票数 1

我正在此地址下载一个pdf文件:

代码语言:javascript
运行
复制
/storage/emulated/0/documents/download folder/2021-08-30-16:37:55.544095iH46x.pdf

它在android 10和更低版本中运行得很好。但是在android 11上我得到了这个错误:

代码语言:javascript
运行
复制
FileSystemException: Cannot open file, path = '/storage/emulated/0/documents/download folder/2021-08-30-16:37:55.544095iH46x.pdf' (OS Error: Operation not permitted, errno = 1)

这些是我对清单的权限:

代码语言:javascript
运行
复制
    <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"/>

这些是我对权限处理程序的权限:

代码语言:javascript
运行
复制
      Map<Permission, PermissionStatus> result = await [
        Permission.storage,
        Permission.manageExternalStorage,
        Permission.mediaLibrary].request();

完整代码:

代码语言:javascript
运行
复制
 String fullPath;
    try {

      Map<Permission, PermissionStatus> result = await [
        Permission.storage,
        Permission.manageExternalStorage,
        Permission.mediaLibrary].request();


      if (result[Permission.storage].isGranted && result[Permission.manageExternalStorage].isGranted && result[Permission.mediaLibrary].isGranted  ) {
        // a custom method for getting path 
        String dir = await Utility.makeAndGetDownloadFolder();
        
        // preparing access token
        final storage = Storage.FlutterSecureStorage();
        String accessToken = await storage.read(key: "accessToken");
         
        // generating random string for the pdf file name
        String dateNow = DateTime.now().toString();
        dateNow = dateNow.replaceAll(' ', '');
        String randomName = dateNow + Utility.getRandomString(5);
        fullPath = "$dir/$randomName.pdf";

        // preparing dio request
        String url;
        Dio dio = Dio();
        Response response;


          url = "https://www.example.com/api/downloadFile";
          FormData formData = FormData.fromMap({
            "idAdvertise": idAdvertise,
          });
          response = await dio.post(url,
              data: formData,
              options: Options(
                  headers: {
                    HttpHeaders.authorizationHeader: 'Bearer $accessToken',
                  },
                  responseType: ResponseType.bytes,
                  followRedirects: false,
                  validateStatus: (status) {
                    return status < 500;
                  }), onReceiveProgress: (int received, int total) {
                if (total != -1) {
                  setState(() {
                    _progress = received / total * 100;
                  });
                }
              });
          if (response.statusCode == 200) {
            File file = File(fullPath);
            // code reach untill here and then it jumps in catch 
            var raf = file.openSync(mode: FileMode.write);
            raf.writeFromSync(response.data);
            await raf.close();
            // show notification on success
            await showNotification(fullPath);
          }else if(response.statusCode == 404){
           // status code 404 do something 
            print("status 404");
          }else{
            print("status code download is ${response.statusCode}");
   Components.customSnackBar(context,AppStr.errDownloadFailed403);
          }
          setState(() {

          });
      } 
    } catch (e) {
      print("catch is $e");
    }

请不要建议我使用path_provider,因为这不是我所需要的

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-06 10:42:18

对于那些仍然想知道我如何解决这个问题的人,我使用路径提供程序将文件保存在缓存中,然后在保存文件之后,将该文件移动到对话框包的下载文件夹中。

源代码:

代码语言:javascript
运行
复制
        //getting the cache directory from path_provider
        Directory dir = await getApplicationDocumentsDirectory();

        final storage = Storage.FlutterSecureStorage();
        String accessToken = await storage.read(key: "accessToken");


        var fileName = Utility.generateRandomFileName();
        fullPath = "${dir.path}/$fileName.pdf";
        bool checkFileExist = true;

        while (checkFileExist) {// if file already exists with this name then we generate different name
          if (await File(fullPath).exists()) {
            fileName = Utility.generateRandomFileName();
            fullPath = "${dir.path}/$fileName.pdf";
          } else {
            checkFileExist = false;
          }
        }

        Dio dio = Dio();
        Response response;
        FormData formData;

          formData = FormData.fromMap({
            "id": widget.id,
          });

        response = await dio.post('https://example.com/downloadfile',
              data: formData,
              options: Options(
                  headers: {
                    HttpHeaders.authorizationHeader: 'Bearer $accessToken',
                  },
                  responseType: ResponseType.bytes,
                  followRedirects: false,
                  validateStatus: (status) {
                    return status < 500;
                  }),
              onReceiveProgress: (int received, int total) {
                if (total != -1) {
                  setState(() {
                    _progressDownloading = received / total * 100;
                  });
                }
              });

          if (response.statusCode == 200) {
              File file = File(fullPath);
              var raf = file.openSync(mode: FileMode.write);
              raf.writeFromSync(response.data);
              await raf.close();

              // moving the file from cache to anywhere you want
              final params = SaveFileDialogParams(sourceFilePath: fullPath);
              await FlutterFileDialog.saveFile(params: params).then((value) async {
                if(value != null){//if the file saved successfully
                  await showNotification();
                }else{
                 print('error couldnt move the pdf file');
                }
              });

              file.delete();//deleting the pdf from cache 
             }else{
               print('something went wrong');
             }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68984682

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档