ASP.NET下檔案下載時重新命名

來源:互聯網
上載者:User

 string FileUlr = Server.MapPath("~/images/test/");//擷取檔案所在目錄

        FileUlr += "5.jpg";//擷取現有檔案所在位置        string OutFileName ="NewFileName";        if (File.Exists(FileUlr))//判斷該檔案是否存在        {            FileInfo fi = new FileInfo(FileUlr);            Response.Clear();            Response.ClearHeaders();            Response.Buffer = false;             string tempfile = Path.GetFileName(FileUlr);//擷取檔案名稱            tempfile = OutFileName + tempfile.Substring(tempfile.LastIndexOf("."));            Response.Clear();            Response.ClearHeaders();            Response.Buffer = false;            // 這一步調試時中文檔案名稱也是正常。             string DownloadFileName = null;            string browser = this.Context.Request.UserAgent.ToUpper();            if (browser.Contains("MS") == true && browser.Contains("IE") == true)//判斷目前使用者使用的瀏覽器類型            {                DownloadFileName = HttpUtility.UrlEncode(tempfile); // 這一步調試時中文檔案名稱也是正常。在ie中中文顯示正常,但在firefox中,中文依然為                //亂碼,所以這裡要判斷使用者使用瀏覽器類型,來保持中文檔案名稱的正常顯示            }            else if (browser.Contains("FIREFOX") == true)            {                DownloadFileName = "\"" + tempfile + "\"";            }            else            {                DownloadFileName = HttpUtility.UrlEncode(tempfile);// 這一步彈出下載儲存的對話方塊,出現檔案名稱亂碼,但變數中的檔案名稱是正常的。            }            Response.AppendHeader("Content-Disposition", "attachment;filename=" + DownloadFileName);//為使用者儲存檔案是顯示的名稱            Response.AppendHeader("Content-Length", fi.Length.ToString());            Response.ContentType = "application/octet-stream";            Response.WriteFile(FileUlr);//用response來返迴文件的路徑            Response.Flush();//清空response            Response.End();        }        else        {            Response.Write("<script langauge=javascript>alert(‘檔案不存在!’);</script>");            Response.End();        }其實該方法的最核心東西就是在  Response.AppendHeader("Content-dispostion","attachment,filename="+DownloadFileName);
這塊 ,Content-dispostion是mime協議的擴充,mime協議指示mime使用者代理程式如何顯示附加的檔案。當Internet Explorer 接收到頭時,他會啟用檔案下載對話方塊,他的檔案明框自動填滿了頭中指定的檔案名稱。這是設計導致的;無法使用此功能將文檔儲存到使用者的電腦上,而不向使用者問詢儲存位置。當然這種情況在ie9中已不存在了,ie9會自動的儲存在一開始設定好的檔案夾下。ie9預設的檔案儲存位置為user/DownLoad檔案夾下。
到這裡,整個下載重新命名就做好了。歡迎提取不同的意見。 摘自:http://www.liushuige.net/newweb/html/news/info.aspx?id=32

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.