如何保存PlatformFile pdf到设备Flutter

zzzyeukh  于 2023-10-22  发布在  Flutter
关注(0)|答案(1)|浏览(114)

我选择了PDF文件作为PlatformFile?selectedPdfFile;我想把它保存回设备我该怎么做我正在使用document_file_保存_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!!')));
    });
  }

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

puruo6ea

puruo6ea1#

您可以使用此代码来保存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);
}

);

  }

相关问题