首页 > 解决方案 > 上传到 Firebase 存储后如何下载 PDF 文件,并在 Flutter 应用程序中显示并保持静态

问题描述

上传到firebase存储后如何下载pdf,并在flutter应用程序中显示并保持静态。

我的意思是当用户访问应用程序中的那个颤动页面或屏幕时,下载的 pdf 文件应该在图标或图像等的点击事件上打开。关闭应用程序后它不应该消失,当我们第二次打开应用程序时.

用户应该能够随时下载和查看或打开 PDF。

这是我尝试过的代码,如下所示:

uploadToFirebase() {
    if (_multiPick) {
        _paths.forEach((fileName, filePath) => {upload(fileName, filePath)});
    } else {
        String fileName = _path.split('/').last;
        String filePath = _path;
        upload(fileName, filePath);
    }
}
 
upload(fileName, filePath) {
    _extension = fileName.toString().split('.').last;
    StorageReference storageRef =
        FirebaseStorage.instance.ref().child(fileName);
    final StorageUploadTask uploadTask = storageRef.putFile(
        File(filePath),
        StorageMetadata(
        contentType: '$_pickType/$_extension',
        ),
    );
    setState(() {
        _tasks.add(uploadTask);
    });
}

Future<void> downloadFile(StorageReference ref) async {
    final String url = await ref.getDownloadURL();
    final http.Response downloadData = await http.get(url);
    final Directory systemTempDir = Directory.systemTemp;
    final File tempFile = File('${systemTempDir.path}/tmp.jpg');
    if (tempFile.existsSync()) {
      await tempFile.delete();
    }
    await tempFile.create();
    final StorageFileDownloadTask task = ref.writeToFile(tempFile);
    final int byteCount = (await task.future).totalByteCount;
    var bodyBytes = downloadData.bodyBytes;
    final String name = await ref.getName();
    final String path = await ref.getPath();
    print(
      'Success!\nDownloaded $name \nUrl: $url'
      '\npath: $path \nBytes Count :: $byteCount',
    );
    _scaffoldKey.currentState.showSnackBar(
      SnackBar(
        backgroundColor: Colors.white,
        content: Image.memory(
          bodyBytes,
          fit: BoxFit.fill,
        ),
      ),
    );
}

此代码仅上传 pdf 文件,但不下载和显示 pdf,因为它正在上传图像和下载,显示图像文件

标签: firebasepdffirebase-storage

解决方案


是的最后我以这种方式将pdf文件上传到firebase存储后成功下载了

    `void  filePicker(BuildContext context) async {
    try {


        PDfFile1 = await FilePicker.getFile(type: FileType.custom, allowedExtensions: ['pdf']);
        fileName = p.basename(PDfFile1.path);
        setState(() {
          fileName = p.basename(PDfFile1.path);
          isPDF_selected=true;
        });
        print(fileName);
       // _uploadFile(PDfFile1, fileName);


    } on PlatformException catch (e) {
      showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text('Sorry...'),
              content: Text('Unsupported exception: $e'),
              actions: <Widget>[
                FlatButton(
                  child: Text('OK'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                )
              ],
            );
          }
      );
    }
  }

  Future<void> _uploadFile(File PDFFile1, String filename) async {

    if (FileType == 'pdf') {



  PDfFile1 = await FilePicker.getFile(type: FileType.custom, allowedExtensions: ['pdf']);
  fileName = p.basename(PDfFile1.path);
  setState(() {
  fileName = p.basename(PDfFile1.path);
  isPDF_selected=true;
  });
  print(fileName);
 // _uploadFile(PDfFile1, fileName);
    }
    final FirebaseStorage _storage4 =
    FirebaseStorage(storageBucket: 'gs://flutter-cb66a.appspot.com');

    //StorageUploadTask uploadTask4;
    String PDFPath = 'DeviceDocs/DeviceDocs${DateTime.now()}.pdf';
   final StorageReference  _storagepdfreference   = FirebaseStorage().ref().child(PDFPath);


     StorageUploadTask uploadTask4 = _storagepdfreference.putFile(PDfFile1);
     StorageTaskSnapshot downloadPDFUrl = (await uploadTask4.onComplete);
     String url = (await downloadPDFUrl.ref.getDownloadURL());
    print("URL is $url");
    setState(() {
      uploadTask4 = _storage4.ref().child('DeviceDocs/DeviceDocs${DateTime.now()}.pdf').putFile(PDfFile1);
      _PDFUploaded= true;
    });
  }

  Future downloadPDfFile1() async {
    String downloadAddress= await _storagepdfreference.getDownloadURL();
    setState(() {
      _downloadPDFUrl= downloadAddress;
    });
  }
`

但现在我想直接从 pdfUrl 打开 pdf。怎么做?


推荐阅读