2013-08-26 54 views
3

這裏是我的代碼,我試圖按照下載文件的功能,但它無法正常工作。它不顯示保存文件對話框。MVC 4文件下載

protected virtual FileResult Download(string FileName, string FilePath) 
{ 

     Response.AppendHeader("Content-Length", FileName.Length.ToString()); 
     return File(FilePath, "application/exe", FileName); 
} 

並試圖通過這種方式也:

protected virtual ActionResult Download(string FileName, string FilePath) 
{ 
    Response.Clear(); 
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName); 
    Response.AppendHeader("Content-Length", FileName.Length.ToString()); 
    Response.ContentType = "application//x-unknown"; 
    Response.WriteFile(FilePath.Replace("\\", "/")); 
    Response.Flush(); 
    Response.End(); 
} 

但都沒有工作。我錯過了什麼?

+0

我希望你對安全有所瞭解問題你的文件路徑和文件名變量會與... – TGlatzer

+0

文件名長度!=內容長度。此外,其可能的瀏覽器阻止可執行文件下載。我知道我的IE瀏覽器確實如此......而Chrome卻拋出了一個「你絕對確定嗎?」提示。 –

+0

看到這個類似的問題:http://stackoverflow.com/questions/3604562/download-file-of-any-type-in​​-as-net-mvc-using-fileresult –

回答

4

我不知道大差別,但下面的代碼工作正常,我的任何文件..可能是因爲ContentType按@Garath建議。

var fileInfo = new System.IO.FileInfo(oFullPath); 
      Response.ContentType = "application/octet-stream"; 
      Response.AddHeader("Content-Disposition", String.Format("attachment;filename=\"{0}\"", yourfilename)); 
      Response.AddHeader("Content-Length", fileInfo.Length.ToString()); 
      Response.WriteFile(oFullPath); 
      Response.End(); 
2

的exe文件的正確mimitype是application/octet-streamapplication/exeapplication//x-unknown - check MSDN 你可以看看這裏的更多定義:Get MIME type from filename extension

+0

我得到的所有東西的權利,但問題是,只有txt文件下載perfactly,但doc文件或pdf文件下載,但在損壞的格式。 –