Dio
dio是一個(gè)強(qiáng)大的Dart Http請(qǐng)求庫,提供了豐富的功能和易于使用的API,支持文件上傳和下載。
這個(gè)就不介紹了,網(wǎng)上有很多的封裝案例。
background_downloader
簡(jiǎn)介
適用于iOS,Android,MacOS,Windows和Linux的后臺(tái)文件下載器和上傳器。
官方文檔
https://pub-web.flutter-io.cn/packages/background_downloader
安裝
flutter pub add background_downloader
示例1:下載
class _MyHomePageState extends State<MyHomePage> {
// 文件信息
String fileInfo = '';
// 下載進(jìn)度
double progress = 0.0;
// 任務(wù)狀態(tài)
String taskStatus = '';
// 任務(wù)
late DownloadTask task;
// 下載單個(gè)文件
_downloadFile() async {
task = DownloadTask(
url:
'https://vd3.bdstatic.com/mda-ma6igm4b0znfbqve/sc/cae_h264_nowatermark/1609998111/mda-ma6igm4b0znfbqve.mp4', // 下載地址
// urlQueryParameters: {'q': 'pizza'}, // 請(qǐng)求參數(shù)
filename: 'mov_bbb.mp4', // 文件名
//headers: {'myHeader': 'value'}, 請(qǐng)求頭
directory: 'my_sub_directory', // 文件存儲(chǔ)目錄
updates: Updates.statusAndProgress, // 更新任務(wù)狀態(tài)和下載進(jìn)度
requiresWiFi: true, // 使用wifi
retries: 5, // 下載的重試次數(shù)
allowPause: true, // 運(yùn)行暫停
metaData: 'data for me' // 元數(shù)據(jù),可以存儲(chǔ)一些對(duì)于下載任務(wù)有用的信息,方便后續(xù)相關(guān)操作
);
// 監(jiān)聽下載
final result =
await FileDownloader().download(task, onProgress: (progress) {
setState(() {
this.progress = progress;
});
}, onStatus: (states) {
String msg = '';
if (states == TaskStatus.complete) {
msg = '下載完成';
// 下載完成后,將文件移動(dòng)到共享目錄后,其他應(yīng)用也可以訪問。否則只能在本應(yīng)用內(nèi)訪問
FileDownloader().moveToSharedStorage(task, SharedStorage.downloads);
} else if (states == TaskStatus.canceled) {
msg = '已取消';
setState(() {
progress = 0;
});
} else if (states == TaskStatus.paused) {
msg = '已暫停';
} else if (states == TaskStatus.running) {
msg = '下載中...';
} else {
msg = '下載失敗';
}
setState(() {
taskStatus = msg;
});
});
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Column(
children: [
const SizedBox(
height: 20,
),
Text("文件信息:$fileInfo"),
const SizedBox(
height: 20,
),
Row(
children: [
const Text("下載進(jìn)度:"),
Expanded(
child: LinearProgressIndicator(
value: progress,
backgroundColor: Colors.greenAccent,
valueColor: const AlwaysStoppedAnimation<Color>(Colors.red),
)),
Text("${(progress * 100).toStringAsFixed(1)}%")
],
),
Text("任務(wù)狀態(tài):$taskStatus"),
const SizedBox(
height: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
mainAxisSize: MainAxisSize.max,
children: [
ElevatedButton(
onPressed: _downloadFile, child: const Text("下載")),
ElevatedButton(
onPressed: () async {
// 暫停任務(wù)
await FileDownloader().pause(task);
},
child: const Text("暫停")),
ElevatedButton(
onPressed: () async {
// 根據(jù)固定的任務(wù)id取消
await FileDownloader().cancelTaskWithId(task.taskId);
// 取消所有
//FileDownloader().cancelTasksWithIds(taskIds)
},
child: const Text("取消")),
ElevatedButton(
onPressed: () async {
await FileDownloader().resume(task);
},
child: const Text("恢復(fù)"))
],
)
],
));
}
}
注意:
- 默認(rèn)下載的文件是在本應(yīng)用內(nèi),其他應(yīng)用無訪問權(quán)限。要想要被訪問到需要在下載完成后執(zhí)行
FileDownloader().moveToSharedStorage(task, SharedStorage.downloads);
- 點(diǎn)擊暫停后,再點(diǎn)擊恢復(fù)可以繼續(xù)下載。點(diǎn)擊取消后,再點(diǎn)擊恢復(fù)無法繼續(xù)下載。
示例2:上傳
/// define the multi-part upload task (subset of parameters shown)
final task = UploadTask(
url: 'https://myserver.com/uploads',
filename: 'myData.txt',
fields: {'datafield': 'value'},
fileField: 'myFile',
updates: Updates.statusAndProgress // request status and progress updates
);
// Start upload, and wait for result. Show progress and status changes
// while uploading
final result = await FileDownloader().upload(task,
onProgress: (progress) => print('Progress: ${progress * 100}%'),
onStatus: (status) => print('Status: $status')
);
// Act on result, similar to download
這個(gè)沒有服務(wù)器,沒有嘗試,上面的是官方例子。
示例3:批量下載
final tasks = [task1, task2, task3]; // a list of Download tasks
// download the batch
final result = await FileDownloader().downloadBatch(tasks,
batchProgressCallback: (succeeded, failed) =>
print('Completed ${succeeded + failed} out of ${tasks.length}, $failed failed')
);
使用DownloadTask
會(huì)返回一個(gè)任務(wù),多個(gè)任務(wù)可以使用downloadBatch
來進(jìn)行批量下載。
示例4:發(fā)起通知
按照官方例子試了一下,一直沒有發(fā)起通知。
我這里的問題是app沒有通知權(quán)限,在設(shè)置里也無法開啟通知。
如果你也沒有成功的話,可以使用flutter_local_notifications
來實(shí)現(xiàn)通知功能
Flutter:flutter_local_notifications——消息推送的學(xué)習(xí)
示例5:打開下載文件
_downloadFile() async {
task = DownloadTask(
url:
'https://ppt.1ppt.com/uploads/soft/2307/1-230H1092638.zip', // 下載地址
// urlQueryParameters: {'q': 'pizza'}, // 請(qǐng)求參數(shù)
filename: '1-230H1092638.zip', // 文件名
//headers: {'myHeader': 'value'}, 請(qǐng)求頭
directory: 'my_sub_directory', // 文件存儲(chǔ)目錄
baseDirectory: BaseDirectory.applicationSupport,
updates: Updates.statusAndProgress, // 更新任務(wù)狀態(tài)和下載進(jìn)度
requiresWiFi: true, // 使用wifi
retries: 5, // 下載的重試次數(shù)
allowPause: true, // 運(yùn)行暫停
metaData: 'data for me' // 元數(shù)據(jù),可以存儲(chǔ)一些對(duì)于下載任務(wù)有用的信息,方便后續(xù)相關(guān)操作
);
// 監(jiān)聽下載
final result =
await FileDownloader().download(task, onProgress: (progress) {
setState(() {
this.progress = progress;
});
}, onStatus: (states) async{
String msg = '';
if (states == TaskStatus.complete) {
msg = '下載完成';
await FileDownloader().openFile(task: task);
print("路徑:${await task.filePath()}");
} else if (states == TaskStatus.canceled) {
msg = '已取消';
setState(() {
progress = 0;
});
} else if (states == TaskStatus.paused) {
msg = '已暫停';
} else if (states == TaskStatus.running) {
msg = '下載中...';
} else {
msg = '下載失敗';
}
setState(() {
taskStatus = msg;
});
});
}
注意:
- 必須要添加
baseDirectory: BaseDirectory.applicationSupport,
,否則是無法打開文件的 - 如果要打開文件,那么就不能使用
FileDownloader().moveToSharedStorage(task, SharedStorage.downloads);
移動(dòng)文件,會(huì)導(dǎo)致找不到文件進(jìn)而打不開。另外打開文件時(shí)會(huì)調(diào)用你手機(jī)里有的應(yīng)用程序打開,我試了一下圖片、mp4
下載完成后是可以直接打開的,但是zip
這樣的文件是無法直接打開的,這時(shí)會(huì)讓你選擇你手機(jī)里的應(yīng)用來打開。
遇到的問題
這是因?yàn)?code>background_downloader要求最小的sdk版本是24,而Flutter會(huì)自動(dòng)設(shè)置minSdkVersion
為16(Android 4.1),在你的Flutter項(xiàng)目的android/app/build.gradle
文件中,將minSdkVersion
更改為24或更高的版本。然后運(yùn)行flutter clean
清理項(xiàng)目,并重新構(gòu)建你的應(yīng)用程序。
從flutter倉庫找到了該問題的解決方案:https://github.com/flutter/flutter/issues/119247文章來源:http://www.zghlxwxcb.cn/news/detail-641019.html
在android / app/build.gradle
文件中添加文章來源地址http://www.zghlxwxcb.cn/news/detail-641019.html
configurations.all {
resolutionStrategy {
eachDependency {
if ((requested.group == "org.jetbrains.kotlin") && (requested.name.startsWith("kotlin-stdlib"))) {
useVersion("1.8.0")
}
}
}
}
到了這里,關(guān)于Flutter:文件上傳與下載(下載后預(yù)覽)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!