簡體   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