java HttpURLConnection 下载的文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10995378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HttpURLConnection downloaded file name
提问by capitano666
Is it possible to get the name of a file downloaded with HttpURLConnection?
是否可以获取使用 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.
在上面的示例中,我无法从 URL 中提取文件名,但服务器会以某种方式向我发送文件名。
回答by 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:
您可以使用HttpURLConnection.getHeaderField(String name)获取Content-Disposition
标题,通常用于设置文件名:
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.
正如其他答案指出的那样,服务器可能会返回无效的文件名,但您可以尝试一下。
回答by Karthik Kumar Viswanathan
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.
坦率的回答是 - 除非 Web 服务器在 Content-Disposition 标头中返回文件名,否则没有真正的文件名。也许您可以将其设置为 / 之后和查询字符串之前的 URI 的最后一部分。
Map m =conn.getHeaderFields();
if(m.get("Content-Disposition")!= null) {
//do stuff
}
回答by Santosh
Check for the Content-Disposition
: attachment header in the response.
检查Content-Disposition
响应中的: 附件标头。
回答by Vijay .D.R
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 ( "]", "" );
}
}