MVC Controller指定されたパスのファイルをダウンロード

1527 ワード

 public void ExportToExcelByName(string fileNames)
        {

            //string filePath = "Z:\\BSS\\" + fileNames;
            //string mapExcelFilesPath =
            ConfigurationManager.RefreshSection("AppSettings");
            string mapExcelFilesPath = ConfigurationManager.AppSettings["MapExcelFilesPath"];
            string filePath = mapExcelFilesPath + fileNames;
            //string filePath = mapExcelFilesPath + fileNames;
            try

            {

                //string DownloadFileName = "~/uploads/" + e.CommandArgument.ToString();//    

                //string filepath = Server.MapPath(DownloadFileName);

                string filename = Path.GetFileName(filePath);

                FileInfo file = new FileInfo(filePath);

                Response.Clear();

                Response.ContentType = "application/octet-stream";

                Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8));

                Response.AddHeader("Content-length", file.Length.ToString());

                Response.Flush();
                
                Response.WriteFile(filePath);

                Response.End();

                file.Delete();

            }

            catch

            {

                Response.Write(filePath+"alert('          ')");

            }


        }