如何从DownloadManager获取下载的文件名 [英] How to get downloaded file name from DownloadManager

查看:69
本文介绍了如何从DownloadManager获取下载的文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在选项卡视图布局中有两个片段.我正在使用WebView()和DownloadManager()下载文件.我的文件下载正常,但是下载的文件没有原始文件名.这是我的问题.如何获得原始文件名?我在这里找到了解决此问题的代码,但没有一个对我有帮助...

I have two fragments in a tab view layout. I am working with WebView() and DownloadManager() to download a file. My file is downloading perfectly but the downloaded file doesn't have the original file name. This is my problem. How do I get the original file name? I found some code here for this issue, but none of them helped me...

这是我正在使用下载管理器的片段:

Here is my fragment where I am using the download manager:

public class Download extends Fragment {
    View v;
    WebView webView2;
    SwipeRefreshLayout mySwipeRefreshLayout;
    DownloadManager downloadManager;

    public String currentUrl = "";
    String myLink = "";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.download, container, false);
        mySwipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swiperefresh);
        webView2 = (WebView) v.findViewById(R.id.webView_download);

        int permissionCheck = ContextCompat.checkSelfPermission(getContext(),
            Manifest.permission.WRITE_EXTERNAL_STORAGE);

        webView2.setInitialScale(1);
        webView2.getSettings().setJavaScriptEnabled(true);
        webView2.getSettings().setLoadWithOverviewMode(true);
        webView2.getSettings().setUseWideViewPort(true);
        webView2.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webView2.setScrollbarFadingEnabled(false);
        webView2.setVerticalScrollBarEnabled(false);
        webView2.loadUrl(currentUrl);
        webView2.setWebViewClient(new WebViewClient());
        webView2.getSettings().setBuiltInZoomControls(true);
        webView2.getSettings().setUseWideViewPort(true);
        webView2.getSettings().setLoadWithOverviewMode(true);
        webView2.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webView2.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                return (event.getAction() == MotionEvent.ACTION_MOVE);
            }
        });

        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
            Bundle bundle = getArguments();

            if (bundle != null) {
                String value = getArguments().getString("link");
                myLink = value;
                webView2.loadUrl(myLink);
            }

            webView2.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));

                    downloadManager = (DownloadManager) getContext().getSystemService(Context.DOWNLOAD_SERVICE);
                    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Youtube_Video" + ".mp4");
                    request.allowScanningByMediaScanner();
                    Long reference = downloadManager.enqueue(request);

                    Toast.makeText(getContext(), "Downloading...", Toast.LENGTH_LONG).show();
                }
            });
        } else {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }

        return v;
    }
}

推荐答案

您将忽略在 onDownloadStart()方法中收到的 contentDisposition 参数-当例如,通过表单提交或POST请求或者有时通过具有重定向功能的GET方法下载文件, Content-disposition 标头通常会包含您要查找的文件名.

You are ignoring the contentDisposition parameter which you are receiving in your onDownloadStart() method — when the file is downloaded for example via a form submit or a POST request or sometimes via a GET method with redirect the Content-disposition header will usually contain the file name that you are looking for.

import android.webkit.URLUtil;

// ...

webView.setDownloadListener(new DownloadListener() {
    public void onDownloadStart(
        String url,
        String userAgent,
        String contentDisposition, // <<< HERE IS THE ANSWER <<<
        String mimetype,
        long contentLength) {

        String humanReadableFileName = URLUtil.guessFileName(url, contentDisposition, mimetype);
        //     ^^^^^^^^^^^^^^^^^^^^^ the name you expect
    // ....


    });

即使 contentDisposition 将包含您的原始文件名,您仍然需要使用BroadcastReceiver来获取实际的内容Uri:

Even though the contentDisposition will contain your original file name you will still need to use a BroadcastReceiver to get the actual content Uri:

    BroadcastReceiver onCompleteHandler = new BroadcastReceiver() {
        public void onReceive(Context ctx, Intent intent) {
            long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
            if (downloadId == downloadRef) {
                Log.d(TAG, "onReceive: " + intent);
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(downloadId);
                Cursor cur = downloadManager.query(query);

                if (cur.moveToFirst()) {
                    int columnIndex = cur.getColumnIndex(DownloadManager.COLUMN_STATUS);
                    if (DownloadManager.STATUS_SUCCESSFUL == cur.getInt(columnIndex)) {
                        String uriString = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));

                        Uri uriDownloadedFile = Uri.parse(uriString);
                        // TODO: consume the uri
                }

            }
        }
    };
    registerReceiver(onCompleteHandler, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

这篇关于如何从DownloadManager获取下载的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆