HttpURLConnection downloaded file name

ⅰ亾dé卋堺 提交于 2019-11-30 05:11:42
Pau Kiat Wee

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.

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
}

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

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 ( "]", "" );
                }
            }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!