简体   繁体   English

尝试使用 Flutter 从 Firebase 下载 PDF

[英]Trying to Download an PDF from Firebase using Flutter

i'm learning how to use Flutter, and in the this .app i'm trying to download a PDF file from firebase final imgUrl = manuais.data()['documento'];我正在学习如何使用 Flutter,在这个 .app 中,我试图从final imgUrl = manuais.data()['documento'];下载 PDF 文件final imgUrl = manuais.data()['documento']; < this final imgURL I use to get the link from Firebase Database. < 我用来从 Firebase 数据库获取链接的最终 imgURL。

This is the error:这是错误:

I/flutter (12444): error is
I/flutter (12444): FileSystemException: Cannot open file, path = '/storage/emulated/0/Download/newtask1.pdf' (OS Error: Operation not permitted, errno = 1)

Here is de code这是 de 代码

import 'dart:typed_data';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:dio/dio.dart';
import 'package:ext_storage/ext_storage.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:esys_flutter_share/esys_flutter_share.dart';
import 'dart:io';
import 'package:flutter_cached_pdfview/flutter_cached_pdfview.dart';
import 'package:permission_handler/permission_handler.dart';





class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  int _currentIndex = 0;






  final tabs = [

    //TAB DE MANUAIS
    Center(
        child: (Scaffold(
            body: StreamBuilder(
                stream: FirebaseFirestore.instance.collection('manuais').snapshots(),
                builder: (context, snapshot) {
                  if (snapshot.data == null) return CircularProgressIndicator();

                  return Container(
                    padding: EdgeInsets.all(16),
                    child: ListView.builder(
                        itemCount: snapshot.data.documents.length,
                        itemBuilder: (context, index) {
                          DocumentSnapshot manuais =
                          snapshot.data.documents[index];

                          final imgUrl = manuais.data()['documento'];

                          var dio = Dio();

                          return Card(
                            color: Colors.grey[250],
                            child: Container(
                              padding: EdgeInsets.all(10),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[

                                  Image.network(manuais.data()['logo'].toString(), width: 32,
                                  ),

                                  Center(
                                    child: Text(
                                      (manuais.data()['nome'].toString()),
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(fontSize: 16),

                                    ),
                                  ),
                                  ButtonBar(
                                    children: <Widget>[



                                      //BOTAO DE DOWNLOAD
                                      FlatButton(
                                          child: const Text('Download'),
                                        onPressed:  () async {
                                            String path =
                                            await ExtStorage.getExternalStoragePublicDirectory(
                                              ExtStorage.DIRECTORY_DOWNLOADS);
                                            String fullPath = '$path/newtask1.pdf';
                                            download2(dio, imgUrl, fullPath);
                                        },




                                      ),
                                        FlatButton(
                                          child: const Text('Compartilhar'),
                                            onPressed: () async {
                                              if (snapshot.data == null) return CircularProgressIndicator();

                                              var request = await HttpClient().getUrl(Uri.parse(manuais.data()['documento']));
                                              var response = await request.close();Uint8List bytes = await consolidateHttpClientResponseBytes(response);
                                              await Share.file(
                                                  'ESYS AMLOG',
                                                  'Manual.pdf',
                                                  bytes,
                                                  'image/jpg');
                                            }),





                                          ],
                                  ),
                                ],
                              ),
                            ),
                          );
                        }),
                  );
                })))),

    //TAB DE PRODUCAO
    Center(
        child: (Scaffold(
            body: StreamBuilder(
                stream: FirebaseFirestore.instance.collection('producao').snapshots(),
                builder: (context, snapshot) {
                  if (snapshot.data == null) return CircularProgressIndicator();

                  return Container(
                    padding: EdgeInsets.all(16),
                    child: ListView.builder(
                        itemCount: snapshot.data.documents.length,
                        itemBuilder: (context, index) {
                          DocumentSnapshot producao =
                          snapshot.data.documents[index];

                          return Card(
                            color: Colors.grey[250],
                            child: Container(
                              padding: EdgeInsets.all(10),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Center(
                                    child: Image.network(producao.data()['img'].toString(), width: 260,
                                    ),
                                  ),
                                  Text(
                                    (producao.data()['data'].toString()),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(fontSize: 22),
                                  ),
                                  Text(
                                    (producao.data()['detail'].toString()),
                                    style: TextStyle(fontSize: 16),
                                  ),
                                  ButtonBar(
                                    children: <Widget>[

                                      FlatButton(
                                          child: const Text('DETALHES'),
                                          onPressed: () {}),
                                      FlatButton(
                                          child: const Text('COMPARTILHAR'),
                                          onPressed: () async {
                                            if (snapshot.data == null) return CircularProgressIndicator();

                                            var request = await HttpClient().getUrl(Uri.parse(producao.data()['img']));
                                            var response = await request.close();Uint8List bytes = await consolidateHttpClientResponseBytes(response);
                                            await Share.file(
                                                'ESYS AMLOG',
                                                'amlog.jpg',
                                                bytes,
                                                'image/jpg');
                                          }),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          );
                        }),
                  );
                })))),
    Center(child: Text('Documentos')),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Área do Cliente')),
      body: tabs[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        type: BottomNavigationBarType.shifting,
        iconSize: 28,
        items: [
          BottomNavigationBarItem(
              icon: Icon(Icons.picture_as_pdf),
              title: Text('Manuais'),
              backgroundColor: Colors.indigo),
          BottomNavigationBarItem(
              icon: Icon(Icons.build),
              title: Text('Produção'),
              backgroundColor: Colors.indigo),
          BottomNavigationBarItem(
            icon: Icon(Icons.folder),
            title: Text('Documentos'),
            backgroundColor: Colors.indigo,
          )
        ],
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
      ),
    );
  }
}

void initState(){
  getPermission();
}
void getPermission() async{
  print('getPermission');
  await PermissionHandler().requestPermissions([PermissionGroup.storage]);

}

Future download2(Dio dio, String url, String savePath) async {
  try{
    var showDownloadProgress;
    Response response = await dio.get(
      url,
      onReceiveProgress: showDownloadProgress,

      options: Options(
        responseType: ResponseType.bytes,
        followRedirects: false,
        validateStatus: (status) {
          return status < 500;
        }),
    );

    File file = File(savePath);
    var raf = file.openSync(mode: FileMode.write);
    raf.writeStringSync(response.data);
    await raf.close();
  } catch (e) {
    print('error is');
    print(e);

  }




}
```
final taskId = await FlutterDownloader.enqueue(
  url: 'your download link',
  savedDir: 'directory/your/folder',
  showNotification: true, // show download progress in status bar (for Android)
  openFileFromNotification: true, // click on notification to open downloaded file (for Android)
);

because u use my package flutter_cached_pdfview因为你使用我的包flutter_cached_pdfview

u don't need to download the pdf file by yourself你不需要自己下载pdf文件

the package can download file, cache it and view包可以下载文件,缓存它并查看

 PDF().cachedFromUrl('your download link'),

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

相关问题 如何使用Android开发中的下载链接从Firebase存储下载pdf文件 - How to download pdf File from Firebase storage using download link in android development 从Firebase Storage下载pdf文件 - Download pdf files from Firebase Storage 尝试使用代码从中下载PDF文件,但未查看PDF文档 - trying a code to download PDF files from but PDF doc is not viewed 尝试从 firebase 获取文件下载 url 时出现 Firebase 错误 - Firebase error when trying to get a file download url from firebase 从 firebase 成功下载 pdf 后,我在真实设备的下载文件夹中找不到 pdf - After successfully download pdf from the firebase I can not find the pdf on the download folder in my real device 使用 dio 从 URL 下载文件 pdf - flutter-download file pdf from URL with dio 从 url 下载 pdf,保存到 android 中 Z5ACEBC4CB70DDBB074B0AC76AAAB176 中的手机本地存储 - Download pdf from url, save to phones local storage in android in flutter Flutter 从 firebase 存储中获取图像并在应用程序中显示以供下载 - Flutter get image from firebase storage and show it in app for download 尝试从带空格的URL下载PDF时使用FileNotFoundExecption - FileNotFoundExecption when trying to download PDF from URL with spaces Firebase 上传/下载 pdf 文件 - Firebase upload/download pdf files
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM