如何将PlatformFile pdf保存到设备flutter

问题描述 投票:0回答:1

我选择了 pdf 文件作为 PlatformFile?选定的 PDF 文件;我想将其保存回设备,我该怎么做,我正在使用 document_file_save_plus 但我的代码中仍然存在错误,有人可以指出哪里出了问题吗

代码

PlatformFile? selectedPdfFile;


  void savePdfToDevice() async {
    final file = File("${selectedPdfFile?.path}/example.pdf");
    Uint8List data = file.readAsBytesSync();

    const fileName = "my_sample_file.pdf";
    const mimeType = "application/pdf";

    setState(() {
      DocumentFileSavePlus().saveFile(data, fileName, mimeType);
      ScaffoldMessenger.of(context)
          .showSnackBar(const SnackBar(content: Text('Saved!!')));
    });
  }

这就是我选择pdf文件的方式

  void _openFilePicker() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['pdf'],
    );
    if (result != null) {
      setState(() {
        selectedPdfFile = result.files.first;
        pdfName = result.files.first.name;
        pdfSize = result.files.first.size;
      });
    } else {
      // User canceled the file picker
    }
  }

它只是说未处理的异常:FileSystemException:无法打开文件,路径='/data/user/0/com.rateraters.lightscan_pro/cache/writerTempFile6632412770717350316.pdf/example.pdf'(操作系统错误:不是目录,errno = 20)我不知道这是什么意思

flutter pdf flutter-dependencies document
1个回答
0
投票

您可以使用此代码在设备上保存 pdf

 String convertCurrentDateTimeToString() {
    return DateFormat('yyyyMMdd_kkmmss').format(DateTime.now());
  }

  Future<void> _downloadFile(String url) async {
    final Dio dio = Dio();
String dirloc = url;
if (Platform.isAndroid) {
  dirloc = "/sdcard/download/";
} else {
  dirloc = (await getApplicationDocumentsDirectory()).path;
  final Directory path = await getApplicationDocumentsDirectory();

  dirloc = '${path.path}${Platform.pathSeparator}Download';

  final savedDir = Directory(dirloc);
  final bool hasExisted = await savedDir.exists();
  if (!hasExisted) {
    savedDir.create();
  }
}

try {
  await dio.download(url, "$dirloc${convertCurrentDateTimeToString()}.pdf",
    onReceiveProgress: (receivedBytes, totalBytes) {
      setState(() {
      });
      // print('here 2');
    },
  );
} catch (e) {
  // print('catch catch catch');
  print(e);
}

setState(() {
  context.showMessage("File successfully save.", true);
}

);

  }
© www.soinside.com 2019 - 2024. All rights reserved.