Android下载文件,如何获取实际的文件名

来源:互联网 发布:网络获客方式 编辑:程序博客网 时间:2024/06/05 18:36

1. 前言


之前APP实现下载文件的功能,都是让后台把下载地址和文件名(包含文件后缀名)传过来。不过近日后台只传了下载地址,我懒得麻烦人家也把文件名传来,所以就自己查资料,想方法解决。


2. 解决方案


解决的办法如下面的代码所示,目前还算能满足要求,如果大伙们有更好的方法,可以在评论说一声


        HttpURLConnection connection = null;        int code = 0;        connection = (HttpURLConnection) new URL(url).openConnection();        connection.setRequestMethod("GET");        connection.setConnectTimeout(8 * 1000);        connection.setReadTimeout(8 * 1000);        connection.connect();        code = connection.getResponseCode();        if (code == HttpURLConnection.HTTP_OK) {                String fileName = connection.getHeaderField("Content-Disposition");                // 通过Content-Disposition获取文件名,这点跟服务器有关,需要灵活变通                if (fileName == null || fileName.length() < 1) {                        // 通过截取URL来获取文件名                        URL downloadUrl = connection.getURL(); // 获得实际下载文件的URL                        fileName = downloadUrl.getFile();                        fileName = fileName.substring(fileName.lastIndexOf("/") + 1);                } else {                        fileName = URLDecoder.decode(fileName.substring(fileName.indexOf("filename=") + 9), "UTF-8");                        // 有些文件名会被包含在""里面,所以要去掉,不然无法读取文件后缀                        fileName = fileName.replaceAll("\"", "");                }        }



原创粉丝点击