如何使用Flutter Dio下载文件?

huangapple go评论70阅读模式
英文:

How can I download file using flutter dio?

问题

I want to downlaod file using url with help of flutter Dio.

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

i am gettng this error.

OS Error: Permission denied, errno = 13flutter

英文:

I want to downlaod file using url with help of flutter Dio.

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


 Future download2(Dio dio, String url, String savePath) async {
    try {
      Response response = await dio.get(
        url,
        onReceiveProgress: showDownloadProgress,
        //Received data with List&lt;int&gt;
        options: Options(
            responseType: ResponseType.bytes,
            followRedirects: false,
            validateStatus: (status) { return status &lt; 500; }
            ),
      );
      print(response.headers);
      File file = File(savePath);
      var raf = file.openSync(mode: FileMode.write);
      // response.data is List&lt;int&gt; 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) + &quot;%&quot;);
    }
  }

i am gettng this error.

OS Error: Permission denied, errno = 13flutter

答案1

得分: 50

以下是您提供的代码的中文翻译部分:

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

代码片段

RaisedButton.icon(
    onPressed: () async {
      var tempDir = await getTemporaryDirectory();
      String fullPath = tempDir.path + "/boo2.pdf";
      print('完整路径 ${fullPath}');

      download2(dio, imgUrl, fullPath);
    },
    icon: Icon(
      Icons.file_download,
      color: Colors.white,
    ),
    color: Colors.green,
    textColor: Colors.white,
    label: Text('下载发票'))
    
工作演示

[![输入图片描述][1]][1]
[![输入图片描述][2]][2]

完整代码

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演示',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter演示首页'),
    );
  }
}

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('完整路径 ${fullPath}');

                  download2(dio, imgUrl, fullPath);
                },
                icon: Icon(
                  Icons.file_download,
                  color: Colors.white,
                ),
                color: Colors.green,
                textColor: Colors.white,
                label: Text('下载发票')),
            Text(
              '您已经按下按钮这么多次:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: '增加',
        child: Icon(Icons.add),
      ),
    );
  }
}

希望这有助于您理解和使用这段代码!

英文:

You can copy paste run full code below <br>
You need to use https://pub.dev/packages/path_provider to get Temporary Directory <br>

code snippet

RaisedButton.icon(
onPressed: () async {
var tempDir = await getTemporaryDirectory();
String fullPath = tempDir.path + &quot;/boo2.pdf&#39;&quot;;
print(&#39;full path ${fullPath}&#39;);
download2(dio, imgUrl, fullPath);
},
icon: Icon(
Icons.file_download,
color: Colors.white,
),
color: Colors.green,
textColor: Colors.white,
label: Text(&#39;Dowload Invoice&#39;))

working demo

如何使用Flutter Dio下载文件?
如何使用Flutter Dio下载文件?

full code

import &#39;package:flutter/material.dart&#39;;
import &#39;package:dio/dio.dart&#39;;
import &#39;package:path_provider/path_provider.dart&#39;;
import &#39;dart:io&#39;;
final imgUrl =
&quot;https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf&quot;;
var dio = Dio();
void main() =&gt; runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: &#39;Flutter Demo&#39;,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: &#39;Flutter Demo Home Page&#39;),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() =&gt; _MyHomePageState();
}
class _MyHomePageState extends State&lt;MyHomePage&gt; {
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&lt;int&gt;
options: Options(
responseType: ResponseType.bytes,
followRedirects: false,
validateStatus: (status) {
return status &lt; 500;
}),
);
print(response.headers);
File file = File(savePath);
var raf = file.openSync(mode: FileMode.write);
// response.data is List&lt;int&gt; 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) + &quot;%&quot;);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: &lt;Widget&gt;[
RaisedButton.icon(
onPressed: () async {
var tempDir = await getTemporaryDirectory();
String fullPath = tempDir.path + &quot;/boo2.pdf&#39;&quot;;
print(&#39;full path ${fullPath}&#39;);
download2(dio, imgUrl, fullPath);
},
icon: Icon(
Icons.file_download,
color: Colors.white,
),
color: Colors.green,
textColor: Colors.white,
label: Text(&#39;Dowload Invoice&#39;)),
Text(
&#39;You have pushed the button this many times:&#39;,
),
Text(
&#39;$_counter&#39;,
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: &#39;Increment&#39;,
child: Icon(Icons.add),
),
);
}
}

答案2

得分: 4

For Android: in 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

your.dart

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

You have to add permissions.

For Android: in 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

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

huangapple
  • 本文由 发表于 2020年1月7日 01:42:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/59616610.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定