如何在flutter中使用dio和pathProvider下载文件

sdnqo3pr  于 2023-05-01  发布在  Flutter
关注(0)|答案(1)|浏览(214)

我试图使用Dio和pathProvider下载文件,但它越来越失败,我尝试了This Soln,但打印进度显示它是下载100%,没有错误抛出,但我找不到下载的文件,我使用Android 13 API 33

void onDownloadClick(String url) async {
    String fileName = url.split("/").last;
    var tempDir = await getTemporaryDirectory();
    String fullPath =tempDir.path.toString() +"/" + fileName;
    debugPrint('full path ${fullPath}');
    var dio = Dio();
    download2(dio, url, fullPath);
  }

  Future download2(Dio dio, String url, String savePath) async {
    try {
      Response response = await dio.get(
        url,
        onReceiveProgress: showDownloadProgress,
        //Received data with List<int>
        options: Options(
            responseType: ResponseType.bytes,
            followRedirects: false,
            validateStatus: (status) {
              return status! < 500;
            },),
      );
      debugPrint(response.headers.toString());
      File file = File(savePath);
      var raf = file.openSync(mode: FileMode.write);
      // response.data is List<int> type
      raf.writeFromSync(response.data);
      await raf.close();

    } catch (e) {
      debugPrint("Got Error  ${e.toString()}");
    }
  }

  void showDownloadProgress(received, total) {
    if (total != -1) {
      debugPrint((received / total * 100).toStringAsFixed(0) + "%");
    }
  }

谢谢

eyh26e7m

eyh26e7m1#

你可以下载你的文件,并保存在你的Android下载文件夹,你可以按照下面的代码.

Directory? directory;
try {
  if (Platform.isIOS) {
    directory = await getApplicationDocumentsDirectory();
  } else {
    directory = await getExternalStorageDirectory();
    String newPath = directory?.path.substring(0, 20) ?? "";
    newPath += "Download";
    directory = Directory(newPath);
    if(!directory.existsSync()){
      await directory.create();
    }
  }
} catch (err) {
  print("download folder not exist");
}

相关问题