String imgurl = "文件地址";
URL url = new URL(imgurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
//获取文件名和扩展名
//先连接一次,解决跳转下载
conn.getResponseCode();
imgurl = conn.getURL().toString();
//第一种方式,针对 img.png
fileName = imgurl.substring(imgurl.lastIndexOf("/")+1);
if(fileName.lastIndexOf(".")>0){
extName = fileName.substring(fileName.lastIndexOf(".")+1);
}
if(extName==null || extName.length()>4 || extName.indexOf("?")>-1){
//第二种方式,获取header 确定文件名和扩展名
fileName = conn.getHeaderField("Content-Disposition");
if(fileName==null || fileName.indexOf("filename")<0){
fileName = enclosure.getId().toString();
extName = "jpg";
}else{
fileName = URLDecoder.decode(fileName.substring(fileName.indexOf("filename")+10,fileName.length()-1),"UTF-8");
extName = fileName.substring(fileName.lastIndexOf(".")+1);
}
}
//还找不到的话,我也没辙了。
Java下载文件获取真实文件名
最新推荐文章于 2024-08-27 10:43:16 发布