Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file name from headers with DownloadManager in Android

I'm using DownloadManager to download video files from a url.

The problem is if I use the default folder to download the file I can not see the video in the galery.

Also, If I try to use this method:

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

I need to know the file name before download which in this case, I don't.

And also, I don't have the name of the file in the url.

How can I do to get the file name from the headers and pass the name to the method setDestinationInExternalPublicDir ? Other alternatives?

like image 456
rodeleon Avatar asked Apr 14 '14 20:04

rodeleon


2 Answers

Small tip, there is a nice helper method in Android

URLUtil.guessFileName(url, contentDisposition, contentType);

So after completing the call to the server, getting the contenttype and contentDisposition from the Headers this will try and find the filename from the information.

like image 77
Raanan Avatar answered Nov 17 '22 09:11

Raanan


In case anyone want an implementation of doing a HEAD request to get the filename:

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) {

    }
}
like image 23
rodeleon Avatar answered Nov 17 '22 09:11

rodeleon