capitano666
capitano666

Reputation: 656

HttpURLConnection downloaded file name

Is it possible to get the name of a file downloaded with HttpURLConnection?

URL url = new URL("http://somesite/getFile?id=12345");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setAllowUserInteraction(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
InputStream is = conn.getInputStream();

In the example above I cannot extract the file name from the URL, but the server will send me the file name in some way.

Upvotes: 14

Views: 22704

Answers (4)

Vijay .D.R
Vijay .D.R

Reputation: 11

Map map = connection.getHeaderFields ();
            if ( map.get ( "Content-Disposition" ) != null )
            {
                String raw = map.get ( "Content-Disposition" ).toString ();
                // raw = "attachment; filename=abc.jpg"
                if ( raw != null && raw.indexOf ( "=" ) != -1 )
                {
                    fileName = raw.split ( "=" )[1]; // getting value after '='
                    fileName = fileName.replaceAll ( "\"", "" ).replaceAll ( "]", "" );
                }
            }

Upvotes: 0

Pau Kiat Wee
Pau Kiat Wee

Reputation: 9505

You could use HttpURLConnection.getHeaderField(String name) to get the Content-Disposition header, which is normally used to set the file name:

String raw = conn.getHeaderField("Content-Disposition");
// raw = "attachment; filename=abc.jpg"
if(raw != null && raw.indexOf("=") != -1) {
    String fileName = raw.split("=")[1]; //getting value after '='
} else {
    // fall back to random generated file name?
}

As other answer pointed out, the server might return invalid file name, but you could try it.

Upvotes: 16

Santosh
Santosh

Reputation: 17903

Check for the Content-Disposition: attachment header in the response.

Upvotes: 0

The frank answer is - unless the web server returns the filename in the Content-Disposition header, there isn't a real filename. Maybe you could set it to the URI's last portion after the /, and before the query string.

Map m =conn.getHeaderFields();
if(m.get("Content-Disposition")!= null) {
 //do stuff
}

Upvotes: 4

Related Questions