HttpURLConnection downloaded file name

前端 未结 4 1041
栀梦
栀梦 2020-12-29 08:19

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

URL url = new URL(\"http://somesite/getFile?id=12345\");
HttpURLConnection conn =         


        
相关标签:
4条回答
  • 2020-12-29 08:55

    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.

    0 讨论(0)
  • 2020-12-29 08:57
    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 ( "]", "" );
                    }
                }
    
    0 讨论(0)
  • 2020-12-29 08:59

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

    0 讨论(0)
  • 2020-12-29 09:21

    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
    }
    
    0 讨论(0)
提交回复
热议问题