2014-11-22 17 views
0

我一直在努力研究這一整天。手指交叉在這裏有人可以幫助我。 :)FileContentResult操作產生不完整的文件

前言:我對ASP非常非常陌生,所以我提前爲我的無知道歉。

目的:我希望能夠通過下載按鈕以各種格式將生成的報告返回給用戶。這些報告生成的很好,並且我已經將它們以字符串格式準備好進行洗牌,以便在某處填充文件。

我們使用剃刀MVC爲我們的網頁,因此我已經得到了下載的ActionLink的,就像這樣:

@Html.ActionLink("CSV", "export", (controller), new { 
         format = "text/csv", 
         #SNIP VARIOUS USER PARAMETERS# 
        }, null) 

這個職位,我們的控制器:

[ActionName("export")] 
[HttpGet] 
public System.Web.Mvc.ActionResult ExportClubs(string format, #PARAMETERS#) 
    { 
     string fileName = "export" + ".csv"; 

     #GENERATE REPORT DATA# 

     string content = #REPORT DATA# 
     // Tried a few different encodings here. 
     byte[] bytes = Encoding.UTF8.GetBytes(content); 

     // many different header configurations tried here too; this is where the examples 
     // tend to vary the most. 
     HttpContext.Current.Response.AddHeader("content-disposition", 
       "attachment; filename=" + fileName); 
     HttpContext.Current.Response.ContentType = format; 

     // Tried many different encodings here as well, including text/csv 
     System.Web.Mvc.FileContentResult file = new System.Web.Mvc.FileContentResult(bytes, System.Net.Mime.MediaTypeNames.Text.Plain); 
     file.FileDownloadName = fileName; 
     return file; 
    } 

所以,只需點擊一下,文件就會以正確的名稱和一切!除了它的內容是這樣的:

{"FileContents":"RGlzd...#SNIP VERY LONG STRING#","ContentType":"text/plain","FileDownloadName":"export.csv"} 

好像有一個最後一步被錯過,什麼地方,採取的是FileContents和重組文件出來,但我不能爲我的生活算起來出。絕對沒有我見過的例子解決這個問題,所以我覺得我一定在某個地方錯過了一些愚蠢的東西。

在此先感謝!

+0

我想,第二個arguemnt,當你實例化FileContentResult應該是你的案例的「文本/ csv」,它正在爲我工​​作 – 2014-11-22 11:09:32

回答

0

你的內容類型是錯誤的,你的代碼時,你實例文件內容結果類的最後一部分應該是這樣的:

// Tried many different encodings here as well, including text/csv 
System.Web.Mvc.FileContentResult file = new System.Web.Mvc.FileContentResult(bytes, "text/csv"); // or what you recieve from arguments 
file.FileDownloadName = fileName; 
return file; 

希望幫助!

+0

這就是我最初的想法,在我開始剔除每一個我能想到的變量之前。不幸的是,沒有什麼區別。 – Metameta 2014-11-24 16:33:24

+0

您有共享內容的問題,這實際上是對象FileContentResult的字符串化json,這是正確的。 ,你有沒有裝飾行動返回爲JSON? ,看起來你錯了 – 2014-11-25 09:37:58