简体   繁体   English

Flutter - 如何在 WebView 中下载文件?

[英]Flutter - How to download files in WebView?

I am using flutter_webview_plugin: ^0.3.8 but I have the same problem with webview_flutter: ^0.3.13 .我正在使用flutter_webview_plugin: ^0.3.8但我对webview_flutter: ^0.3.13 : ^0.3.13 有同样的问题。

In webview, I want to make use of a website which triggers a file download on successful completion of a captcha.在 webview 中,我想使用一个在成功完成验证码时触发文件下载的网站。 However, I complete the captcha and nothing happens, no download.但是,我完成了验证码,没有任何反应,没有下载。

Is there something in Flutter like a webview download listener ("webview.setDownloadListener")? Flutter 中是否有类似 webview 下载监听器(“webview.setDownloadListener”)的东西? I only need this for Android.我只需要这个用于Android。

If not, is there a way of downloading files from a webview in Flutter?如果没有,有没有办法从 Flutter 中的 webview 下载文件?

A similar issue can be found here !可以在这里找到类似的问题!

You can use my plugin flutter_inappwebview , which is a Flutter plugin that allows you to add inline WebViews or open an in-app browser window and has a lot of events, methods, and options to control WebViews.你可以使用我的插件flutter_inappwebview ,它是一个 Flutter 插件,允许你添加内联 WebView 或打开应用内浏览器窗口,并且有很多事件、方法和选项来控制 WebView。 It can recognize downloadable files in both Android (using setDownloadListener ) and iOS platforms!它可以识别 Android(使用setDownloadListener )和 iOS 平台中的可下载文件!

I report here the same answer that I gave to the similar issue:我在这里报告我对类似问题给出的相同答案

To be able to recognize downloadable files, you need to set the useOnDownloadStart: true option, and then you can listen the onDownloadStart event!为了能够识别可下载的文件,需要设置useOnDownloadStart: true选项,然后才能监听onDownloadStart事件!

Also, for example, on Android you need to add write permission inside your AndroidManifest.xml file:此外,例如,在 Android 上,您需要在AndroidManifest.xml文件中添加写入权限:

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

Then, you need to ask permission using the permission_handler plugin.然后,您需要使用permission_handler插件请求许可。 Instead, to effectively download your file, you can use the flutter_downloader plugin.相反,为了有效地下载文件,您可以使用flutter_downloader插件。

Here is a complete example using http://ovh.net/files/ (in particular, the http://ovh.net/files/1Mio.dat as URL) to test the download:这是一个使用http://ovh.net/files/ (特别是http://ovh.net/files/1Mio.dat作为 URL)来测试下载的完整示例:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await FlutterDownloader.initialize(
      debug: true // optional: set false to disable printing logs to console
  );
  await Permission.storage.request();
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  InAppWebViewController webView;

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

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('InAppWebView Example'),
        ),
        body: Container(
            child: Column(children: <Widget>[
          Expanded(
              child: InAppWebView(
            initialUrl: "http://ovh.net/files/1Mio.dat",
            initialHeaders: {},
            initialOptions: InAppWebViewGroupOptions(
              crossPlatform: InAppWebViewOptions(
                debuggingEnabled: true,
                useOnDownloadStart: true
              ),
            ),
            onWebViewCreated: (InAppWebViewController controller) {
              webView = controller;
            },
            onLoadStart: (InAppWebViewController controller, String url) {

            },
            onLoadStop: (InAppWebViewController controller, String url) {

            },
            onDownloadStart: (controller, url) async {
              print("onDownloadStart $url");
              final taskId = await FlutterDownloader.enqueue(
                url: url,
                savedDir: (await getExternalStorageDirectory()).path,
                showNotification: true, // show download progress in status bar (for Android)
                openFileFromNotification: true, // click on notification to open downloaded file (for Android)
              );
            },
          ))
        ])),
      ),
    );
  }
}

Here, as you can see, I'm using also the path_provider plugin to get the folder where I want to save the file.在这里,如您所见,我还使用path_provider插件来获取要保存文件的文件夹。

just add this code to your AndroidManifest.xml只需将此代码添加到您的 AndroidManifest.xml

   <provider
            android:name="vn.hunghd.flutterdownloader.DownloadedFileProvider"
            android:authorities="${applicationId}.flutter_downloader.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
    </provider>

and add this code to your AndroidManifest.xml并将此代码添加到您的 AndroidManifest.xml

it works to me它对我有用

it works for me这个对我有用

require plugin https://pub.dev/packages/url_launcher需要插件https://pub.dev/packages/url_launcher

add this code to your project to download file from flutter webview将此代码添加到您的项目中以从 Flutter webview 下载文件

onDownloadStart: (controller, url,) async {
                    // print("onDownloadStart $url");
                    final String _url_files = "$url";
                    void _launchURL_files() async =>
                        await canLaunch(_url_files) ? await launch(_url_files) : throw 'Could not launch $_url_files';
                    _launchURL_files();
                  },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM