繁体   English   中英

URL中的文件名不包含文件名后缀

[英]Filename from URL not containing filename suffix

我需要从URL下载一个文件,除了我不知道该文件的类型和我使用的URL在其末尾没有/random.file所以我无法解析该URL的URL文档名称。 目前我正在使用Android下载管理器,它运行很好,意味着我没有处理下载,但我无论如何都看不到它下载的文件中的文件名。 如果我在Firefox中加载相同的URL,例如它询问'下载文件:Nameoffile.extension'。

在下载文件之前,有没有办法让我复制此行为并获取文件名?

您最好在响应中读取HTTP Content-Type标头并确定它是什么类型的文件。 文件扩展名不保证文件的类型。 Content-Disposition: attachment; filename="fname.ext" 如果您具体说明文件名,则Content-Disposition: attachment; filename="fname.ext"是另一种方法。 查看HTTP标头列表以获取更多信息。

我最终使用ASyncTask手动检索文件名并将其传递给下载管理器,如果它帮助任何人这就是我做的方式(我的url在实际文件下载之前经历了一些重定向):

class GetFileInfo extends AsyncTask<String, Integer, String>
{
    protected String doInBackground(String... urls)
    {
                URL url;
                String filename = null;
                try {
                    url = new URL(urls[0]);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.connect();
                conn.setInstanceFollowRedirects(false); 

                try {
                    for(int i = 0; i < 10; i++)
                    {
                        url = new URL(conn.getHeaderField("Location")); 
                        conn = (HttpURLConnection) url.openConnection();
                        conn.connect();
                        conn.setInstanceFollowRedirects(false);
                    }
                } catch (Exception e) {
                }

                String depo = conn.getHeaderField("Content-Disposition");
                String depoSplit[] = depo.split(";");
                int size = depoSplit.length;
                for(int i = 0; i < size; i++)
                {
                    if(depoSplit[i].startsWith("filename="))
                    {
                        filename = depoSplit[i].replace("filename=", "").replace("\"", "").trim();
                        Global.error(filename);
                        i = size;
                    }
                }
                } catch (MalformedURLException e1) {
                    e1.printStackTrace();
                } catch (IOException e) {
                }
            return filename;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM