Flutter 下载文件到手机下载目录 [英] Flutter download file to phone download directory

查看:529
本文介绍了Flutter 下载文件到手机下载目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索过类似的问题和这个问题的答案,但直到现在还没有找到任何具体的答案.我正在尝试将下载的文件保存到我的内部手机存储中.最好是下载文件夹...我正在使用 d i o 和路径提供程序.已尝试使用获取外部存储目录".但即使下载后,我也无法在设备中的任何位置找到该文件.请问如何指定下载路径到/storage/emulated/0/Download

解决方案

您可以在下面复制粘贴运行完整代码
此示例代码使用 Dio 下载 pdf 文件并保存到 Downloads 目录
第 1 步:downloads_path_provider 已被所有者归档,您可以使用包

完整代码

import 'package:flutter/material.dart';导入包:dio/dio.dart";导入'包:ext_storage/ext_storage.dart';导入飞镖:io";导入'包:permission_handler/permission_handler.dart';最终 imgUrl =https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";var dio = dio();void main() =>运行应用程序(我的应用程序());class MyApp 扩展 StatelessWidget {@覆盖小部件构建(BuildContext 上下文){返回 MaterialApp(title: 'Flutter 演示',主题:主题数据(主要色板:Colors.blue,),home: MyHomePage(title: 'Flutter Demo Home Page'),);}}class MyHomePage 扩展 StatefulWidget {MyHomePage({Key key, this.title}) : super(key: key);最终字符串标题;@覆盖_MyHomePageState createState() =>_MyHomePageState();}class _MyHomePageState 扩展 State{int_counter = 0;void _incrementCounter() {设置状态((){_计数器++;});}void getPermission() 异步 {打印(获取权限");映射权限 =等待 PermissionHandler().requestPermissions([PermissionGroup.storage]);}@覆盖无效的初始化状态(){获取权限();super.initState();}未来下载 2(Dio dio, String url, String savePath) async {尝试 {响应 response = await dio.get(网址,onReceiveProgress: showDownloadProgress,//用List接收到的数据选项:选项(responseType: ResponseType.bytes,跟随重定向:假,验证状态:(状态){返回状态<500;}),);打印(响应.标题);文件文件 = 文件(保存路径);var raf = file.openSync(mode: FileMode.write);//response.data 是 List类型raf.writeFromSync(response.data);等待 raf.close();}赶上(e){打印(e);}}void showDownloadProgress(received, total) {如果(总计!= -1){打印((接收/总* 100).toStringAsFixed(0)+%");}}@覆盖小部件构建(BuildContext 上下文){返回脚手架(应用栏:应用栏(标题:文本(小部件.标题),),身体:中心(孩子:列(mainAxisAlignment: MainAxisAlignment.center,孩子们:<小部件>[凸起按钮.icon(onPressed: () 异步 {字符串路径 =等待 ExtStorage.getExternalStoragePublicDirectory(ExtStorage.DIRECTORY_DOWNLOADS);//String fullPath = tempDir.path + "/boo2.pdf'";String fullPath = "$path/test.pdf";print('完整路径 ${fullPath}');下载2(dio, imgUrl, fullPath);},图标:图标(Icons.file_download,颜色:Colors.white,),颜色:Colors.green,textColor: Colors.white,标签:文本('下载')),文本('你按了这么多次按钮:',),文本('$_counter',样式:Theme.of(context).textTheme.display1,),],),),浮动动作按钮:浮动动作按钮(onPressed: _incrementCounter,工具提示:'增量',孩子:图标(Icons.add),),);}}

I have searched for similar questions and answers to this question but haven't found any specific answer till now. I am trying to save downloaded files to my internal phone storage. Preferably the download folder... Am using d i o and path provider. Have tried using "get External Storage Directory". But even after the download I can't locate the file anywhere in my device. Please how do I specify the download path to something like /storage/emulated/0/Download

解决方案

You can copy paste run full code below
This example code download a pdf file with Dio and save to Downloads directory
Step 1: downloads_path_provider has archived by the owner, you can use package https://pub.dev/packages/ext_storage
code snippet

String path = await ExtStorage.getExternalStoragePublicDirectory(
    ExtStorage.DIRECTORY_DOWNLOADS);
print(path);

Step 2: Add permission in AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Step 3: pubspec.yaml , notice permission_handler is 4.4.0

dependencies:
  flutter:
    sdk: flutter
  dio: any
  permission_handler: 4.4.0
  ext_storage: any

Step 4: Dio for download file

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;
            }),
      );
      print(response.headers);
      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) {
      print(e);
    }
  }

output

I/flutter (13605): full path /storage/emulated/0/Download/test.pdf
I/flutter (13605): 62%
I/flutter (13605): 100%

full code

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:ext_storage/ext_storage.dart';
import 'dart:io';
import 'package:permission_handler/permission_handler.dart';

final imgUrl =
    "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";

var dio = Dio();

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      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> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  void getPermission() async {
    print("getPermission");
    Map<PermissionGroup, PermissionStatus> permissions =
        await PermissionHandler().requestPermissions([PermissionGroup.storage]);
  }

  @override
  void initState() {
    getPermission();
    super.initState();
  }

  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;
            }),
      );
      print(response.headers);
      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) {
      print(e);
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton.icon(
                onPressed: () async {
                  String path =
                      await ExtStorage.getExternalStoragePublicDirectory(
                          ExtStorage.DIRECTORY_DOWNLOADS);
                  //String fullPath = tempDir.path + "/boo2.pdf'";
                  String fullPath = "$path/test.pdf";
                  print('full path ${fullPath}');

                  download2(dio, imgUrl, fullPath);
                },
                icon: Icon(
                  Icons.file_download,
                  color: Colors.white,
                ),
                color: Colors.green,
                textColor: Colors.white,
                label: Text('Dowload')),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

这篇关于Flutter 下载文件到手机下载目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆