【问题标题】:Download file inside WebView在 WebView 中下载文件
【发布时间】:2012-04-09 04:56:08
【问题描述】:

我的 Android 应用程序中有一个 webview。当用户转到 webview 并单击链接以下载文件时,没有任何反应。

URL = "my url";
mWebView = (WebView) findViewById(R.id.webview);
mWebView.setWebViewClient(new HelloWebViewClient());
mWebView.getSettings().setDefaultZoom(ZoomDensity.FAR);
mWebView.loadUrl(URL);
Log.v("TheURL", URL);

如何在 webview 中启用下载?如果我禁用 webview 并启用从应用程序在浏览器上加载 URL 的意图,则下载将无缝运行。

String url = "my url";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);

有人可以帮我吗?页面加载没有问题,但 HTML 页面中图像文件的链接不起作用...

【问题讨论】:

标签: android webview download attachment


【解决方案1】:

你试过了吗?

mWebView.setDownloadListener(new DownloadListener() {
    public void onDownloadStart(String url, String userAgent,
                String contentDisposition, String mimetype,
                long contentLength) {
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(url));
        startActivity(i);
    }
});

示例链接:Webview File Download - 谢谢@c49

【讨论】:

  • 此代码有效,但如果用户在 WebView 中通过了身份验证,则一旦 Android 浏览器启动,他们就会被要求再次登录,之后就会发生下载。我正在尝试找到一种方法来避免这种情况,因此无需他们再次登录即可进行下载。
  • 尝试此链接进行任何类型的下载androidtrainningcenter.blogspot.in/2013/11/…
  • @ioSamurai 你有没有找到一种下载需要用户身份验证的文件的方法。 webView.setDownloadListener() 在不需要用户身份验证时完美运行。但是当我从谷歌驱动器或其他需要用户身份验证的来源下载文件时,会下载一个文件但没有数据。 @user370305 你也可以帮忙。
  • 您可以查看Chrome Custom tabs,这将解决大部分问题。 @Rohit
  • @Sp4Rx 是的,它适用于此,但我需要一些仅适用于 webview 的其他功能
【解决方案2】:

试试这个。在浏览了很多帖子和论坛后,我发现了这一点。

mWebView.setDownloadListener(new DownloadListener() {       

    @Override
    public void onDownloadStart(String url, String userAgent,
                                    String contentDisposition, String mimetype,
                                    long contentLength) {
            DownloadManager.Request request = new DownloadManager.Request(
                    Uri.parse(url));

            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Name of your downloadble file goes here, example: Mathematics II ");
            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            dm.enqueue(request);
            Toast.makeText(getApplicationContext(), "Downloading File", //To notify the Client that the file is being downloaded
                    Toast.LENGTH_LONG).show();

        }
    });

不要忘记授予此权限!这个非常重要!将此添加到您的清单文件中(AndroidManifest.xml 文件)

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />        <!-- for your file, say a pdf to work -->

希望这会有所帮助。 干杯:)

【讨论】:

  • 感谢成功!使用原始文件名,我们可以使用:final String filename= URLUtil.guessFileName(url, contentDisposition, mimetype);
  • @SaiZ 您的示例包含一些关于未使用意图的代码,我想您应该删除它。
  • @j.c 我删除了未使用的代码,感谢您的报告;)
  • 这是一个完美的答案,它将直接从 webview 启动下载,这实际上是预期的......谢谢
  • @Jawaad 感谢您的回复。不过我还是一头雾水。我什至不知道要打开哪个文件。我尝试在整个解决方案中搜索request.setDestinationInExternalPublicDir,但没有匹配项。 #xamarin-forms
【解决方案3】:
    mwebView.setDownloadListener(new DownloadListener()
   {

  @Override  


   public void onDownloadStart(String url, String userAgent,
        String contentDisposition, String mimeType,
        long contentLength) {

    DownloadManager.Request request = new DownloadManager.Request(
            Uri.parse(url));


    request.setMimeType(mimeType);


    String cookies = CookieManager.getInstance().getCookie(url);


    request.addRequestHeader("cookie", cookies);


    request.addRequestHeader("User-Agent", userAgent);


    request.setDescription("Downloading file...");


    request.setTitle(URLUtil.guessFileName(url, contentDisposition,
            mimeType));


    request.allowScanningByMediaScanner();


    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    request.setDestinationInExternalPublicDir(
            Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
                    url, contentDisposition, mimeType));
    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    dm.enqueue(request);
    Toast.makeText(getApplicationContext(), "Downloading File",
            Toast.LENGTH_LONG).show();
}});

【讨论】:

  • 请解释一下你写了什么。光有代码是不够的
  • 设置 cookie 拯救了我的一天!谢谢!
  • 这应该被接受的答案,工作。谢谢朋友
  • 我正在使用网络视图从 Digi-locker 下载文档,但使用相同的代码 sn-p 下载失败。文件格式为pdf。谁能帮帮我。
【解决方案4】:

尝试使用下载管理器,它可以帮助您下​​载所需的所有内容并节省您的时间。

勾选这些选项:

选项 1 ->

 mWebView.setDownloadListener(new DownloadListener() {
        public void onDownloadStart(String url, String userAgent,
                String contentDisposition, String mimetype,
                long contentLength) {
 Request request = new Request(
                            Uri.parse(url));
                    request.allowScanningByMediaScanner();
                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download"); 
                    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                    dm.enqueue(request);        

        }
    });

选项 2 ->

if(mWebview.getUrl().contains(".mp3") {
 Request request = new Request(
                        Uri.parse(url));
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download"); 
// You can change the name of the downloads, by changing "download" to everything you want, such as the mWebview title...
                DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                dm.enqueue(request);        

    }

【讨论】:

    【解决方案5】:
    webView.setDownloadListener(new DownloadListener()
            {
                @Override
                public void onDownloadStart(String url, String userAgent,
                                            String contentDisposition, String mimeType,
                                            long contentLength) {
                    DownloadManager.Request request = new DownloadManager.Request(
                            Uri.parse(url));
                    request.setMimeType(mimeType);
                    String cookies = CookieManager.getInstance().getCookie(url);
                    request.addRequestHeader("cookie", cookies);
                    request.addRequestHeader("User-Agent", userAgent);
                    request.setDescription("Downloading File...");
                    request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
                    request.allowScanningByMediaScanner();
                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                    request.setDestinationInExternalPublicDir(
                            Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
                                    url, contentDisposition, mimeType));
                    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                    dm.enqueue(request);
                    Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
                }});
    

    【讨论】:

    • 感谢您的回答!
    【解决方案6】:

    如果您不想使用下载管理器,那么您可以使用此代码

    webView.setDownloadListener(new DownloadListener() {
    
                @Override
                public void onDownloadStart(String url, String userAgent, String contentDisposition
                        , String mimetype, long contentLength) {
    
                    String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype);
    
                    try {
                        String address = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"
                                + Environment.DIRECTORY_DOWNLOADS + "/" +
                                fileName;
                        File file = new File(address);
                        boolean a = file.createNewFile();
    
                        URL link = new URL(url);
                        downloadFile(link, address);
    
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
    
     public void downloadFile(URL url, String outputFileName) throws IOException {
    
            try (InputStream in = url.openStream();
                 ReadableByteChannel rbc = Channels.newChannel(in);
                 FileOutputStream fos = new FileOutputStream(outputFileName)) {
                fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            }
               // do your work here
    
        }
    

    这将下载手机存储中下载文件夹中的文件。如果你想在后台下载它,你可以使用线程(使用 thread.alive() 和计时器类来知道下载是否完成)。这在我们下载小文件时很有用,因为您可以在下载后立即执行下一个任务。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-16
      • 1970-01-01
      • 1970-01-01
      • 2017-05-01
      • 2014-08-13
      • 1970-01-01
      • 2020-03-10
      相关资源
      最近更新 更多