gpt4 book ai didi

android - 如何从互联网下载文件并将其保存到 Flutter/dart 的内部存储(android)?

转载 作者:行者123 更新时间:2023-12-03 17:31:28 28 4
gpt4 key购买 nike

我需要将文件 eg.jpg 保存到“internalstorage/appname/files/”
并在文件夹中已存在通知时显示通知。当按下按钮/启动 Activity 时,它应该使用 dart 代码将文件下载到安卓设备的本地存储。
帮我找到解决方案。

**code:**
import 'dart:io';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import './landing_page.dart';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
import 'package:simple_permissions/simple_permissions.dart';
import 'package:flutter/services.dart';


class MoviesPage extends StatefulWidget {

@override
State createState() => new MoviesPageState();
}

class MoviesPageState extends State<MoviesPage> {
final dUrl ="https://cdn.putlockers.es/download/0BBCA7584749D4E741747E32E6EB588AEA03E40F";
bool downloading = false;
var progressString = "";
static const MethodChannel _channel =
const MethodChannel('flutter_downloader');

@override
void initState() {
super.initState();
downloadFile();

}


Future<void> downloadFile() async {
Dio dio = Dio();

try {
var dir = await getApplicationDocumentsDirectory();

await dio.download(dUrl, "${dir.path}/file.torrent",
onProgress: (rec, total) {
print("Rec: $rec , Total: $total");

setState(() {
downloading = true;
progressString = ((rec / total) * 100).toStringAsFixed(0) + "%";
});
});
} catch (e) {
print(e);
}

setState(() {
downloading = false;
progressString = "Completed";
});
print("Download completed");
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("AppBar"),
),
body: Center(
child: downloading
? Container(
height: 120.0,
width: 200.0,
child: Card(
color: Colors.black,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircularProgressIndicator(),
SizedBox(
height: 20.0,
),
Text(
"Downloading File: $progressString",
style: TextStyle(
color: Colors.white,
),
)
],
),
),
)
: Text("No Data"),
),
);
}
}

在此先感谢。以完整的方式发布您的解决方案。

最佳答案

我检查了您发布的最小复制,您似乎正在使用 Flutter 插件 dio下载文件。我重用了Future<void> downloadFile()从您的代码中并对其进行一些修改以检查插件是否按预期工作。从 dio 插件 3.0.10 版开始,onProgressdio.download()现在是 onReceiveProgress ,但它本质上仍然具有相同的功能。
这是从您的代码下载图像文件并稍作修改的方法。

Future downloadFile() async {
Dio dio = Dio();
var dir = await getApplicationDocumentsDirectory();
var imageDownloadPath = '${dir.path}/image.jpg';
await dio.download(imageSrc, imageDownloadPath,
onReceiveProgress: (received, total) {
var progress = (received / total) * 100;
debugPrint('Rec: $received , Total: $total, $progress%');
setState(() {
downloadProgress = received.toDouble() / total.toDouble();
});
});
// downloadFile function returns path where image has been downloaded
return imageDownloadPath;
}
该插件按预期工作并成功下载图像文件。虽然我无法验证您如何确定您尝试下载的图像在您的复制品上失败。在我的示例应用程序中, Future downloadFile()返回存储图像路径的字符串。然后我使用它来更新图像小部件以显示下载的图像 - 这确定下载已经成功。
这是完整的示例应用程序。
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);

final String title;

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
final imageSrc = 'https://picsum.photos/250?image=9';
var downloadPath = '';
var downloadProgress = 0.0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(flex: 5, child: Image.network(imageSrc)),
Expanded(
flex: 2,
child: Row(
children: [
ElevatedButton(
// Download displayed image from imageSrc
onPressed: () {
downloadFile().catchError((onError) {
debugPrint('Error downloading: $onError');
}).then((imagePath) {
debugPrint('Download successful, path: $imagePath');
displayDownloadImage(imagePath);
});
},
child: Text('Download'),
),
ElevatedButton(
// Delete downloaded image
onPressed: () {
deleteFile().catchError((onError) {
debugPrint('Error deleting: $onError');
}).then((value) {
debugPrint('Delete successful');
});
},
child: Text('Clear'),
)
],
),
),
LinearProgressIndicator(
value: downloadProgress,
),
Expanded(
flex: 5,
child: downloadPath == ''
// Display a different image while downloadPath is empty
// downloadPath will contain an image file path on successful image download
? Icon(Icons.image)
: Image.file(File(downloadPath))),
],
),
),
);
}

displayDownloadImage(String path) {
setState(() {
downloadPath = path;
});
}

Future deleteFile() async {
final dir = await getApplicationDocumentsDirectory();
var file = File('${dir.path}/image.jpg');
await file.delete();
setState(() {
// Clear downloadPath on file deletion
downloadPath = '';
});
}

Future downloadFile() async {
Dio dio = Dio();
var dir = await getApplicationDocumentsDirectory();
var imageDownloadPath = '${dir.path}/image.jpg';
await dio.download(imageSrc, imageDownloadPath,
onReceiveProgress: (received, total) {
var progress = (received / total) * 100;
debugPrint('Rec: $received , Total: $total, $progress%');
setState(() {
downloadProgress = received.toDouble() / total.toDouble();
});
});
// downloadFile function returns path where image has been downloaded
return imageDownloadPath;
}
}
在示例应用程序中,单击“下载”按钮将在下载的屏幕顶部显示网络图像。下载成功后,会显示下载的图片使用 Image.file()在屏幕的下部。
enter image description here

关于android - 如何从互联网下载文件并将其保存到 Flutter/dart 的内部存储(android)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53158245/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com