Flutter下载文件、获取进度及存储

一、前言

应用内下载文件时可使用,基于dio的下载文件

二、引用

dio

功能:网络请求。

地址:https://pub.dev/packages/dio

path_provider

功能:提供访问文件系统的插件。

地址:https://pub.dev/packages/path_provider

三、使用

  1. 生成存储文件地址
  2. get下载文件及获取下载进度
  3. 写入文件
import 'dart:io';

import 'package:dio/dio.dart';

import 'package:path_provider/path_provider.dart';

/// 获取app文件地址
Directory storageDir = await getApplicationDocumentsDirectory();
String storagePath = storageDir.path;
File file = new File('$storagePath/世界上有趣的事太多.epub');

if (!file.existsSync()) {
  file.createSync();
}

/// dio使用get下载文件
try{
  var response = await Dio().get(
    "http://ds.addsxz.com/912sjsyqds.epu",
    onReceiveProgress: (num received, num total){ /// 获取下载进度
      double _process = double.parse('${(received / total).toStringAsFixed(2)}');
      print(_process);
    },
    options: Options(
      responseType: ResponseType.bytes,
      followRedirects: false,
    )
  );
  file.writeAsBytesSync(response.data); /// 写入文件
  return file;
} on DioError catch(e) {
  print("response.statusCode: ${e.type}");
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Flutter 是一个跨平台的移动应用程序开发框架,可以快速构建具备丰富用户界面和功能的应用程序。在Flutter的开发中,文件下载是不可避免的需求,经常遇到需要下载文件的场景,例如下载图片、音频以及视频等媒体文件或其他数据文件Flutter 提供了许多第三方库来实现文件下载,常用的有http、dio等库,这些库都可以配合Flutter的异步特性来下载文件,并提供了丰富的参数设置和进度回调信息。 在使用http库进行文件下载时,可以通过设置请求头信息为字节范围来支持断点续传,即如果下载中断可以继续下载,避免重复下载浪费流量和时间。同时,还可以通过设置连接和读取超时时间等参数来优化下载体验。使用http库下载文件的代码示例如下: ``` import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:io'; import 'dart:async'; class DownloadFile extends StatefulWidget { @override _DownloadFileState createState() => _DownloadFileState(); } class _DownloadFileState extends State<DownloadFile> { String downloadUrl = "http://www.example.com/file.mp3"; String savePath = Directory.systemTemp.path + "/file.mp3"; Future<void> _downloadFile(String url, String savePath) async { final response = await http.get(url, headers: { HttpHeaders.rangeHeader: "bytes=${File(savePath).lengthSync()}-" }).timeout(Duration(seconds: 30)); if (response.statusCode == 200 || response.statusCode == 206) { File(savePath).writeAsBytesSync(response.bodyBytes, mode: FileMode.append); } else { throw Exception("Download failed: ${response.statusCode}"); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Download file example"), ), body: Center( child: RaisedButton( onPressed: () { _downloadFile(downloadUrl, savePath); }, child: Text("Download file"), ), ), ); } } ``` 在上述代码中,使用dio下载文件也可以实现类似的功能,而且dio库有更加方便的操作和更加详细的错误处理和进度监听功能。需要注意的是,使用dio库需要在pubspec.yaml文件中添加依赖库: ``` dependencies: dio: ^3.0.10 ``` 使用dio下载文件的代码示例如下: ``` import 'package:flutter/material.dart'; import 'package:dio/dio.dart'; import 'dart:io'; import 'dart:async'; class DownloadFile extends StatefulWidget { @override _DownloadFileState createState() => _DownloadFileState(); } class _DownloadFileState extends State<DownloadFile> { String downloadUrl = "http://www.example.com/file.mp3"; String savePath = Directory.systemTemp.path + "/file.mp3"; Future<void> _downloadFile(String url, String savePath) async { Dio dio = Dio(); try { Response response = await dio.download( url, savePath, onReceiveProgress: (count, total) => print("Received $count bytes out of $total"), options: Options(headers: { HttpHeaders.rangeHeader: "bytes=${File(savePath).lengthSync()}-" }), ); } catch (e) { throw Exception("Download failed: $e"); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Download file example"), ), body: Center( child: RaisedButton( onPressed: () { _downloadFile(downloadUrl, savePath); }, child: Text("Download file"), ), ), ); } } ``` 综上所述,Flutter提供了多种库可以实现文件下载功能,选择合适的库可以有效地提升下载效率和下载体验,进一步提升应用的用户体验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

倾云鹤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值