2014-11-22 19 views
2

我開發一個asp.net - MVC應用程序,並具有以下問題: 當用戶鍵入特定的URL,在我的情況:ASP MVC - 下載一個文件,然後導航到一個視圖

http://localhost/Download 

我希望它去的操作方法,下載一個文件,然後導航到相應的視圖的操作方法:

我的代碼看起來像這樣:

public ActionResult Index() 
    { 
     string filePath = WebConfigurationManager.AppSettings["Download"]; 

     FileInfo file = new FileInfo(filePath); 

     if (file.Exists) 
     { 
      Response.Clear(); 

      Response.ClearHeaders(); 

      Response.ClearContent(); 

      Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); 

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

      Response.ContentType = "text/plain"; 


      Response.TransmitFile(file.FullName); 

      Response.Flush(); 

      Response.End(); 
     } 


     return View(); 
    } 

我的視域L ooks,因爲它得到簡單:

@{ 
ViewBag.Title = "Index"; 
} 
<h2>Downloading ...</h2> 

當我運行它,我得到的文件,但它並不導航到視圖,而是停留在之前的URL。

編輯 - 回答: 感謝@Abbas Galiyakot 的回覆。

這裏是更新的代碼,做我想要的東西:

public ActionResult Index() 
    { 
     return View(); 
    } 


    public ActionResult DownloadFile() 
    { 
     string filePath = WebConfigurationManager.AppSettings["Download"]; 

     FileInfo file = new FileInfo(filePath); 

     if (file.Exists) 
     { 
      Response.Clear(); 

      Response.ClearHeaders(); 

      Response.ClearContent(); 

      Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); 

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

      Response.ContentType = "text/plain"; 


      Response.TransmitFile(file.FullName); 

      Response.Flush(); 

      Response.End(); 
     } 

     return new EmptyResult(); 

    } 





@{ 
    ViewBag.Title = "Index"; 
} 

<h2>Downloading...</h2> 


<script type="text/javascript"> 
    window.location.href = '@Url.Action("DownloadFile", "Home")'; 
</script> 

回答

2

每個HTTP請求只能有一個反應 - 你想在兩到潛行(文件和頁面)。

通常,當您發送「Content-Disposition:attachment」HTTP標頭時,瀏覽器將停留在當前頁面並彈出文件保存對話框(或自動將文件保存在您的下載中)。

你將不得不改變你的策略。在新窗口中打開此頁面(下載文件)並使用javascript進行重定向。

+0

謝謝阿巴斯!你已經解釋得很好! – DimaK 2014-11-22 11:06:40

相關問題