Java.io.FileNotFoundException:在真实的Android设备上打开失败:EACCES(权限被拒绝)

5

我的目标是从API服务器下载文件(本例中为PDF文件),然后在UI上加载该PDF并显示。我正在使用flutter_pdfview,并按照此教程实现它。首先,需要权限:在我的android/app/build.gradle中,targetSdkVersioncompileSdkVersion都是29。在android/app/main/AndroidManifest.xml中,我写了以下内容:<application ... android:requestLegacyExternalStorage="true">,并在同一文件夹中添加了这些权限。

<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"/>

获取请求:

Future<File> getFile(String id) async {
    _isLoading = true;
    notifyListeners();
    var headers = {
      'Authorization': 'JWT ${_authenticatedUser.token}',
      'Content-Type': 'application/x-www-form-urlencoded',
      'Accept': 'application/json',
    };
    try {
      final http.Response response = await http.get(
          'api-host/pdf',
          headers: headers);
      var bytes = response.bodyBytes;
      var dir = await getExternalStorageDirectory();// Option 1
      //var dir = awiat getApplicationDocumentsDirectory(); //Option 2
      File file = File("${dir.path}/mypdfonline.pdf");
      File urlFile = await file.writeAsBytes(bytes);
      if (response.statusCode != 200) {
        _isLoading = false;
        notifyListeners();
        throw Exception('get error: statusCode= ${response.headers}');
      }
      _isLoading = false;
      notifyListeners();
      return urlFile;
    } catch (e) {
      _isLoading = false;
      notifyListeners();
      throw Exception("Error opening url file");
    }
  }

选项一,我在我的内部存储中找到了PDF文件,但仍然出现错误。像那个人所做的那样使用选项二,在我的设备上无法找到它。此外,我已经在手机上手动授予了存储访问权限,但这也没有帮助。


class ImagePreview extends StatefulWidget {
  final MainModel model;
  final String id;
  ImagePreview(this.model, this.id);
  @override
  State<StatefulWidget> createState() {
    return _ImagePreviewState();
  }
}

class _ImagePreviewState extends State<ImagePreview> {
  String urlPDFPath = "";
  int _totalPages = 0;
  int _currentPage = 0;
  bool pdfReady = false;
  PDFViewController _pdfViewController;
  @override
  void initState() {
    super.initState();
    widget.model.getFile(widget.id).then((value) {
      setState(() {
        urlPDFPath = value.path;
        print(urlPDFPath);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('PDF Preview'),
      ),
      body: Stack(
        children: <Widget>[
          PDFView(
            filePath: urlPDFPath,
            autoSpacing: true,
            enableSwipe: true,
            pageSnap: true,
            swipeHorizontal: true,
            nightMode: false,
            onError: (e) {
              print(e);
            },
            onRender: (_pages) {
              setState(() {
                _totalPages = _pages;
                pdfReady = true;
              });
            },
            onViewCreated: (PDFViewController vc) {
              _pdfViewController = vc;
            },
            onPageChanged: (int page, int total) {
              setState(() {});
            },
            onPageError: (page, e) {},
          ),
          !pdfReady
              ? Center(
                  child: CircularProgressIndicator(),
                )
              : Offstage(),
        ],
      ),
      floatingActionButton: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          _currentPage > 0
              ? FloatingActionButton.extended(
                  backgroundColor: Colors.red,
                  label: Text("Go to ${_currentPage - 1}"),
                  onPressed: () {
                    _currentPage -= 1;
                    _pdfViewController.setPage(_currentPage);
                  },
                )
              : Offstage(),
          _currentPage + 1 < _totalPages
              ? FloatingActionButton.extended(
                  backgroundColor: Colors.green,
                  label: Text("Go to ${_currentPage + 1}"),
                  onPressed: () {
                    _currentPage += 1;
                    _pdfViewController.setPage(_currentPage);
                  },
                )
              : Offstage(),
        ],
      ),
    );
  }
}

同样的错误在这里。 - Darmawan Z.
1个回答

0

您需要存储权限才能在设备存储上写入数据。您可以使用permission_handler插件来管理存储权限。

// Check for existing storage permission
if (await Permission. storage.request().isGranted) {
  // Run after verifying storage permission
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接