使用Android WebView下载图片

3
我想在我的Webview中下载图像。我使用了如下的链接标签:
<a href="../Temp/Images/def.jpg" download="">Download</div></a>

在Chrome浏览器上运行良好,但在我的Webview应用程序中无法运行。我已经激活了几个权限。
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />

但是链接仍然没有反应。我如何触发下载?
编辑:
响应标头:
Cache-Control:private
Connection:Close
Content-Disposition:attachment; filename=IMG_20141004_171308.jpg
Content-Length:3039432
Content-Type:image/jpeg
Date:Wed, 15 Oct 2014 12:35:57 GMT
Server:ASP.NET Development Server/10.0.0.0
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:4.0
3个回答

8
尝试添加下载监听器 -
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 folder
                "download");                        //Name of file


                DownloadManager dm = (DownloadManager) getSystemService(
                DOWNLOAD_SERVICE);

                dm.enqueue(request);  

    }
});

1
有帮助。谢谢!编辑:但它只下载当前URL,我得到的是HTML文件而不是图片。 - zanzoken
你知道我怎么能获取这个jpg文件吗?我已经在我的帖子中更新了请求。 - zanzoken
你拥有这个网站吗? - Confuse

6
我有同样的问题。这是我解决它的方法。我扩展了WebViewClient:
import java.io.File;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.webkit.WebView;
import android.webkit.WebViewClient;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MyWebViewClient extends WebViewClient {

    private Context context;

    public MyWebViewClient(Context context) {
        this.context = context;
    }

    @SuppressLint("NewApi")
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if(url.contains(".jpg")){

            DownloadManager mdDownloadManager = (DownloadManager) context  
                    .getSystemService(Context.DOWNLOAD_SERVICE);  
            DownloadManager.Request request = new DownloadManager.Request(  
                    Uri.parse(url));  
            File destinationFile = new File(  
                    Environment.getExternalStorageDirectory(),  
                    getFileName(url));  
            request.setDescription("Downloading ...");  
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);  
            request.setDestinationUri(Uri.fromFile(destinationFile));  
            mdDownloadManager.enqueue(request);  


            return true;
        }
        return super.shouldOverrideUrlLoading(view, url);
    }

    public String getFileName(String url) {  
        String filenameWithoutExtension = "";  
        filenameWithoutExtension = String.valueOf(System.currentTimeMillis()  
                + ".jpg");  
        return filenameWithoutExtension;  
    }  


}

当然,您可以修改URL过滤器,例如大写字母等其他扩展...
在Fragment中,添加以下行:
webPreview.setWebViewClient(new MyWebViewClient(getActivity()));

或者在Activity中添加以下代码:

webPreview.setWebViewClient(new MyWebViewClient(this));

当然,将webPreview修改为您设置的WebView名称。
确保将以下内容添加到WebView设置中:
webSettings.setDomStorageEnabled(true);

如果您已经设置了:
webSettings.setBlockNetworkImage (false);

我使用这段代码时出现了错误 java.lang.SecurityException: No permission to write to /storage/emulated/0/1499081348105.jpg: Neither user 10109 nor current process has android.permission.WRITE_EXTERNAL_STORAGE。 - Ankit Prajapati
1
@AnkitPrajapati 我认为这是因为您在应用程序清单中没有允许WRITE_EXTERNAL_STORAGE权限。 - I'l Follio
@I'l Follio,感谢您的回答,但我读到API >=23需要运行时权限,我是这样做的 https://stackoverflow.com/questions/44882785/android-webview-not-triggering-a-href-download-file/44884557?noredirect=1#comment76821699_44884557 - Ankit Prajapati

0

API 30及以上版本中,正确的工作代码。 请确保在清单文件中添加以下权限。

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


  webView.setDownloadListener(new DownloadListener() {


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

            Log.i("KAMLESH","Download Image Request  "+url);

            if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
            {
                requestForPermissions(permissionsRequired);
                return;
            }

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

            request.setNotificationVisibility(
                    DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download");                        //Name of file

            File file =  new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOWNLOADS), "image_" + System.currentTimeMillis() + ".jpg");
            file.getParentFile().mkdirs();

            request.setDestinationUri(Uri.fromFile(file));

            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

            dm.enqueue(request);



        }
    });


void requestForPermissions(String permissions[])
{
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Need Permission");
    builder.setMessage("This app needs Storage permission.");
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

            dialog.cancel();
            ActivityCompat.requestPermissions(WebViewActivity.this, permissionsRequired, 1);


        }
    });

    builder.show();

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接