【问题标题】:How can I download file using flutter dio?如何使用颤振 dio 下载文件?
【发布时间】:2020-04-24 06:18:39
【问题描述】:

我想在 Flutter Dio 的帮助下使用 url 下载文件。

  final imgUrl = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";
  var dio = Dio();
RaisedButton.icon(
                  onPressed: (){
                    download2(dio, imgUrl, "./example/boo2.pdf");
                  },
                  icon: Icon(Icons.file_download,color: Colors.white,),
                  color: Colors.green,
                  textColor: Colors.white,
                  label: Text('Dowload Invoice')
              )


 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) + "%");
    }
  }

我遇到了这个错误。

操作系统错误:权限被拒绝,errno = 13flutter

【问题讨论】:

    标签: android ios http flutter dart


    【解决方案1】:

    您可以在下面复制粘贴运行完整代码
    您需要使用https://pub.dev/packages/path_provider 获取临时目录

    代码sn-p

    RaisedButton.icon(
                    onPressed: () async {
                      var tempDir = await getTemporaryDirectory();
                      String fullPath = tempDir.path + "/boo2.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 Invoice'))
    

    工作演示

    完整代码

    import 'package:flutter/material.dart';
    import 'package:dio/dio.dart';
    import 'package:path_provider/path_provider.dart';
    import 'dart:io';
    
    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++;
        });
      }
    
      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 {
                      var tempDir = await getTemporaryDirectory();
                      String fullPath = tempDir.path + "/boo2.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 Invoice')),
                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),
          ),
        );
      }
    }
    

    【讨论】:

    • 如果我想将此文件存储在我的下载文件夹中,我该如何提供路径?
    • 表示我要存储下载文件的任何特定位置。
    • 你不能做任何文件夹,Android较新版本中的大部分文件夹都受到保护。您可以在 getTemporaryDirectory() 中创建一个文件夹
    • 但是下载的文件没有显示在我的手机中。
    • 如果您不授予写入外部存储的权限,则会发生错误
    【解决方案2】:

    您必须添加权限。

    对于 Android:在 AndroidManifest.xml 中

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

    pubspec.yaml

    ext_storage: ^1.0.3

    你的.dart

      @override
      void initState() {
        getPermission();
        super.initState();
      }
    
      //get storage permission
      void getPermission() async {
        await PermissionHandler().requestPermissions([PermissionGroup.storage]);
      }
    

    【讨论】:

      猜你喜欢
      • 2020-03-10
      • 2021-04-12
      • 2021-06-10
      • 1970-01-01
      • 1970-01-01
      • 2020-01-15
      • 2022-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多