//利用檔案下載頁,並將檔案放在虛擬目錄外的地方。

        string fileName = string.Empty;

        if (Request.QueryString["fileName"]!= null && Request.QueryString["fileName"].Length > 0)

            fileName =Server.UrlDecode(Request.QueryString["fileName"]);

 

        ////或用Post取值

        //if (Request.Form["fileName"] != null &&Request.Form["fileName"].Length > 0)

        //    fileName =Server.UrlDecode(Request.Form["fileName"]);

 

        if (fileName.Length == 0)

        {

           Response.Write("No Filename.");

            return;//跳出

        }

 

        string RamdomPath = "1234567";

        string ActualPath = Server.MapPath(string.Format("~/{0}/",RamdomPath));//利用MapPath取得主機上的實際目錄

        //ActualPath="C:\RamdomPath"; //或直接指定目錄

 

        DirectoryInfo dir = newDirectoryInfo(ActualPath); //取得目錄資訊

        if (dir.Exists) //判斷是否存在

        {

            FileInfo file = newFileInfo(fileName);

 

            //FileInfo[] infos = dir.GetFiles(fileName);//取得接近的檔名,可以用萬用符號

            //if(infos.Length > 0)

            //    file =infos[0];

 

            if (file.Exists)

            {

                string downloadfilename = file.Name;//建立需要的檔案名稱

 

                //準備下載檔案

               Response.ClearHeaders();//清除標頭

               Response.Clear();//清除輸出,只讓檔案輸出

               Response.Expires = 0;//取消過期時間

               Response.Buffer = false;

               Response.ContentType = "application/save-as";//指定瀏覽器另存新檔

               Response.AddHeader("Content-Disposition","attachment;filename=" +Server.UrlEncode(downloadfilename)); //组合下载的文件名

               Response.AddHeader("Content-Length",file.Length.ToString()); // 指定文件大小,讓瀏覽器能夠顯示下載進度

               Response.TransmitFile(file.FullName);//需使用完整的名稱

               Response.Flush(); //把緩衝取出

                Response.Close();//關閉連線

               Response.End();//結束

                return;

            }

            else

            {

               Response.Write("No File inDirectory.");

                return;//跳出

            }

        }

        else

        {

           Response.Write("No Directory.");

            return;//跳出

        }

arrow
arrow
    全站熱搜

    ikaritw 發表在 痞客邦 留言(2) 人氣()