使用Android中的DownloadManager从标头中获取文件名

问题描述 投票:5回答:4

我正在使用DownloadManager从网址下载视频文件。

问题是如果我使用默认文件夹下载文件,我无法在galery中看到视频。

另外,如果我尝试使用此方法:

request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, 'filename');

我需要在下载之前知道文件名,在这种情况下,我不知道。

而且,我在网址中没有该文件的名称。

如何从标头中获取文件名并将名称传递给方法setDestinationInExternalPublicDir?其他选择?

android android-download-manager
4个回答
9
投票

如果有人想要执行HEAD请求来获取文件名:

class GetFileName extends AsyncTask<String, Integer, String>
{
    protected String doInBackground(String... urls)
    {
        URL url;
        String filename = null;
        try {
            url = new URL(urls[0]);
            String cookie = CookieManager.getInstance().getCookie(urls[0]);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestProperty("Cookie", cookie);
            con.setRequestMethod("HEAD");
            con.setInstanceFollowRedirects(false);
            con.connect();

            String content = con.getHeaderField("Content-Disposition");
            String contentSplit[] = content.split("filename=");
            filename = contentSplit[1].replace("filename=", "").replace("\"", "").trim();
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
        }
        return filename;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected void onPostExecute(String result) {

    }
}

1
投票

小技巧,Android中有一个很好的帮手方法

URLUtil.guessFileName(url, contentDisposition, contentType);

因此,在完成对服务器的调用之后,从Headers获取内容类型和内容Disposition将尝试从信息中找到文件名。


0
投票

我遇到了同样的问题。我使用了@rodeleon的答案,但响应头中没有Content-Disposition。然后我分析了Chrome开发工具中的url标题,并在响应标题中得到了“位置”,其中包含文件结尾,就像“b / Ol / fire_mp3_24825.mp3”。所以不要使用

String content = con.getHeaderField("Content-Disposition")

我用了

String content = con.getHeaderField("Location") 

并在onPostExecute的最后

    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        String fileName = result.substring(result.lastIndexOf("/") + 1);
        // use result as file name
        Log.d("MainActivity", "onPostExecute: " + fileName);
    }

-3
投票
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_MOVIES, uri.getLastPathSegment());
© www.soinside.com 2019 - 2024. All rights reserved.