Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从url下载pdf,保存到手机的android本地存储_Android_Api_Flutter - Fatal编程技术网

从url下载pdf,保存到手机的android本地存储

从url下载pdf,保存到手机的android本地存储,android,api,flutter,Android,Api,Flutter,我正在做一个项目,这需要我从URL下载一个pdf文件,一旦点击一个按钮,并将其存储到手机存储器(可能是下载文件夹) 有什么办法吗?正在下载的文件也不总是相同的,可以是从pdf到图像的任何文件。您可以使用软件包使用Dio()将文件下载到本地存储。下载 response = await dio.download("https://www.google.com/", "./xx.html"); 此外,您还可以将此作为参考签出您可以使用该软件包使用Dio()将文件下载到本地存储。下载 response

我正在做一个项目,这需要我从URL下载一个pdf文件,一旦点击一个按钮,并将其存储到手机存储器(可能是下载文件夹)

有什么办法吗?正在下载的文件也不总是相同的,可以是从pdf到图像的任何文件。

您可以使用软件包使用
Dio()将文件下载到本地存储。下载

response = await dio.download("https://www.google.com/", "./xx.html");
此外,您还可以将此作为参考签出

您可以使用该软件包使用
Dio()将文件下载到本地存储。下载

response = await dio.download("https://www.google.com/", "./xx.html");

您也可以将此作为参考查看

我希望这会对您有所帮助。检查文件是否已经存在,如果不存在,则使用URL获取文件并将其保存在应用程序目录中

Future<File> createFile() async {
    try {
      /// setting filename 
      final filename = widget.docPath;

      /// getting application doc directory's path in dir variable
      String dir = (await getApplicationDocumentsDirectory()).path;

      /// if `filename` File exists in local system then return that file.
      /// This is the fastest among all.
      if (await File('$dir/$filename').exists()) return File('$dir/$filename');

      ///if file not present in local system then fetch it from server

      String url = widget.documentUrl;

      /// requesting http to get url
      var request = await HttpClient().getUrl(Uri.parse(url));

      /// closing request and getting response
      var response = await request.close();

      /// getting response data in bytes
      var bytes = await consolidateHttpClientResponseBytes(response);

      /// generating a local system file with name as 'filename' and path as '$dir/$filename'
      File file = new File('$dir/$filename');

      /// writing bytes data of response in the file.
      await file.writeAsBytes(bytes);

      /// returning file.
      return file;
    }

    /// on catching Exception return null
    catch (err) {
      errorMessage = "Error";
      print(errorMessage);
      print(err);
      return null;
    }
  }
Future createFile()异步{
试一试{
///设置文件名
最终文件名=widget.docPath;
///在dir变量中获取应用程序文档目录的路径
字符串dir=(等待getApplicationDocumentsDirectory()).path;
///如果本地系统中存在“filename”文件,则返回该文件。
///这是最快的。
if(等待文件('$dir/$filename').exists())返回文件('$dir/$filename');
///若本地系统中不存在文件,则从服务器获取该文件
字符串url=widget.documentUrl;
///正在请求http以获取url
var request=wait HttpClient().getUrl(Uri.parse(url));
///关闭请求并获取响应
var response=wait request.close();
///以字节为单位获取响应数据
var bytes=等待合并HttpClientResponseBytes(响应);
///正在生成名为“filename”且路径为“$dir/$filename”的本地系统文件
File File=新文件(“$dir/$filename”);
///在文件中写入响应的字节数据。
等待文件。writeAsBytes(字节);
///正在返回文件。
返回文件;
}
///捕获异常时返回null
捕捉(错误){
errorMessage=“Error”;
打印(错误消息);
打印(错误);
返回null;
}
}

我希望这会对您有所帮助。检查文件是否已经存在,如果不存在,则使用URL获取文件并将其保存在应用程序目录中

Future<File> createFile() async {
    try {
      /// setting filename 
      final filename = widget.docPath;

      /// getting application doc directory's path in dir variable
      String dir = (await getApplicationDocumentsDirectory()).path;

      /// if `filename` File exists in local system then return that file.
      /// This is the fastest among all.
      if (await File('$dir/$filename').exists()) return File('$dir/$filename');

      ///if file not present in local system then fetch it from server

      String url = widget.documentUrl;

      /// requesting http to get url
      var request = await HttpClient().getUrl(Uri.parse(url));

      /// closing request and getting response
      var response = await request.close();

      /// getting response data in bytes
      var bytes = await consolidateHttpClientResponseBytes(response);

      /// generating a local system file with name as 'filename' and path as '$dir/$filename'
      File file = new File('$dir/$filename');

      /// writing bytes data of response in the file.
      await file.writeAsBytes(bytes);

      /// returning file.
      return file;
    }

    /// on catching Exception return null
    catch (err) {
      errorMessage = "Error";
      print(errorMessage);
      print(err);
      return null;
    }
  }
Future createFile()异步{
试一试{
///设置文件名
最终文件名=widget.docPath;
///在dir变量中获取应用程序文档目录的路径
字符串dir=(等待getApplicationDocumentsDirectory()).path;
///如果本地系统中存在“filename”文件,则返回该文件。
///这是最快的。
if(等待文件('$dir/$filename').exists())返回文件('$dir/$filename');
///若本地系统中不存在文件,则从服务器获取该文件
字符串url=widget.documentUrl;
///正在请求http以获取url
var request=wait HttpClient().getUrl(Uri.parse(url));
///关闭请求并获取响应
var response=wait request.close();
///以字节为单位获取响应数据
var bytes=等待合并HttpClientResponseBytes(响应);
///正在生成名为“filename”且路径为“$dir/$filename”的本地系统文件
File File=新文件(“$dir/$filename”);
///在文件中写入响应的字节数据。
等待文件。writeAsBytes(字节);
///正在返回文件。
返回文件;
}
///捕获异常时返回null
捕捉(错误){
errorMessage=“Error”;
打印(错误消息);
打印(错误);
返回null;
}
}

以下代码在iOS和Android上都适用。如果要下载图像,请将“.pdf”替换为“.jpg”

pubspec.yaml
中,将下面的代码粘贴到dependencies下

dio: any
path_provider: any
file_utils: any
permission_handler: any
android/app/src/main/AndroidManifest.xml中,将下面的行粘贴到
标记之外

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

代码如下:

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:async';
import 'package:file_utils/file_utils.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:intl/intl.dart';

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

class Downloader extends StatelessWidget {
  @override
  Widget build(BuildContext context) => MaterialApp(
    title: "File Downloader",
    debugShowCheckedModeBanner: false,
    home: FileDownloader(),
    theme: ThemeData(primarySwatch: Colors.blue),
  );
}

class FileDownloader extends StatefulWidget {
  @override
  _FileDownloaderState createState() => _FileDownloaderState();
}

class _FileDownloaderState extends State<FileDownloader> {

final pdfUrl = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";
  
  bool downloading = false;
  var progress = "";
  var path = "No Data";
  var platformVersion = "Unknown";
  var _onPressed;
  Directory externalDir;

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

String convertCurrentDateTimeToString() {
    String formattedDateTime =
    DateFormat('yyyyMMdd_kkmmss').format(DateTime.now()).toString();
    return formattedDateTime;
  }

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

    final status = await Permission.storage.request();
    if (status.isGranted) {
      String dirloc = "";
      if (Platform.isAndroid) {
        dirloc = "/sdcard/download/";
      } else {
        dirloc = (await getApplicationDocumentsDirectory()).path;
      }

      try {
        FileUtils.mkdir([dirloc]);
        await dio.download(pdfUrl, dirloc + convertCurrentDateTimeToString() + ".pdf",
            onReceiveProgress: (receivedBytes, totalBytes) {
          print('here 1');
              setState(() {
                downloading = true;
                progress = ((receivedBytes / totalBytes) * 100).toStringAsFixed(0) + "%";
                print(progress);
              });
              print('here 2');
            });
      } catch (e) {
        print('catch catch catch');
        print(e);
      }

      setState(() {
        downloading = false;
        progress = "Download Completed.";
        path = dirloc + convertCurrentDateTimeToString() + ".pdf";
      });
      print(path);
      print('here give alert-->completed');
    } else {
      setState(() {
        progress = "Permission Denied!";
        _onPressed = () {
          downloadFile();
        };
      });
    }
  }

  @override
  Widget build(BuildContext context) => Scaffold(
      appBar: AppBar(
        title: Text('File Downloader'),
      ),
      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: 10.0,
                  ),
                  Text(
                    'Downloading File: $progress',
                    style: TextStyle(color: Colors.white),
                  ),
                ],
              ),
            ),
          )
              : Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(path),
              MaterialButton(
                child: Text('Request Permission Again.'),
                onPressed: _onPressed,
                disabledColor: Colors.blueGrey,
                color: Colors.pink,
                textColor: Colors.white,
                height: 40.0,
                minWidth: 100.0,
              ),
            ],
          )));
}
导入'dart:io';
进口“包装:颤振/材料.省道”;
进口“包装:dio/dio.dart”;
导入“package:path_provider/path_provider.dart”;
导入“dart:async”;
导入“package:file_utils/file_utils.dart”;
导入“package:permission_handler/permission_handler.dart”;
导入“包:intl/intl.dart”;
void main()=>runApp(Downloader());
类Downloader扩展了无状态小部件{
@凌驾
小部件构建(构建上下文)=>MaterialApp(
标题:“文件下载程序”,
debugShowCheckedModeBanner:false,
主页:FileDownloader(),
主题:主题数据(原始样本:颜色。蓝色),
);
}
类FileDownloader扩展StatefulWidget{
@凌驾
_FileDownloaderState createState();
}
类_FileDownloaderState扩展状态{
最终pdfUrl=”https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";
bool=false;
var progress=“”;
var path=“无数据”;
var platformVersion=“未知”;
var_onPressed;
目录externalDir;
@凌驾
void initState(){
super.initState();
下载文件();
}
字符串convertCurrentDateTimeToString(){
字符串格式化日期时间=
DateFormat('yyyyymmdd_kkmmss').format(DateTime.now()).toString();
返回格式化日期时间;
}
Future downloadFile()异步{
Dio Dio=Dio();
最终状态=wait Permission.storage.request();
如果(status.isgrated){
字符串dirloc=“”;
if(Platform.isAndroid){
dirloc=“/sdcard/download/”;
}否则{
dirloc=(等待getApplicationDocumentsDirectory()).path;
}
试一试{
mkdir([dirloc]);
等待dio.download(pdfUrl,dirloc+convertCurrentDateTimeToString()+“.pdf”,
onReceiveProgress:(receivedBytes,totalBytes){
打印(“此处1”);
设置状态(){
下载=真;
进度=((接收字节/总字节)*100);
印刷(进度);
});