Get file name from headers using DownloadManager in Android

I am using DownloadManager to download video files from a URL.

The problem is that if I use the default folder to upload the file, I do not see the video in the gallery.

Also, if I try to use this method:

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

I need to know the file name before downloading, in which case I am not .

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

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

+5
source share
4 answers

If someone wants to execute a HEAD request to get the file name:

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

    }
}
+9

, Android

URLUtil.guessFileName(url, contentDisposition, contentType);

, , contenttype contentDisposition .

+1

. Content-Disposition. URL- Chrome dev "Location" , , "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);
    }
0
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_MOVIES, uri.getLastPathSegment());
-3

Source: https://habr.com/ru/post/1536504/


All Articles