2012-11-27 57 views
0

我正在生成一個我不想讓用戶下載的小Json文件。所以我希望瀏覽器提示用戶下載文件。無法讓瀏覽器下載json文件intead將其寫入響應

我已經嘗試了許多在相關問題中提出的答案,但這些不會對我有用。

@Ajax.ActionLink("Generate JSON", "GenerateOcJson", new AjaxOptions { HttpMethod = "POST" }) 

我已經試過:

var cd = new System.Net.Mime.ContentDisposition { FileName = fileName, Inline = false }; 
Response.AppendHeader("Content-Disposition", cd.ToString()); 

return File(Encoding.UTF8.GetBytes(jsonString), 
      "application/json", 
      string.Format(fileName)); 

和:

請求是通過在ActionLink的點擊做出

Response.Clear(); 
Response.ContentType = "application/json"; 
Response.AppendHeader("Content-Disposition", "attachment; filename=foo.json"); 
Response.Write(jsonString); 
Response.End(); 

但瀏覽器不會下載文件。我使用的是MVC3,這個方法是由actionlink調用的。我試過POST和GET請求。

如果我用Chrome檢查請求,我看到正確的json已經寫入瀏覽器響應。

任何線索? Thnx

+0

你爲什麼內容類型設置爲「應用程序/ PDF」如果是JSON?不應該是'application/json'或'text/javascript'(有幾種可能性,參見[http://stackoverflow.com/questions/477816/the-right-json-content-type](http:/ /stackoverflow.com/questions/477816/the-right-json-content-type)) – MadSkunk

+0

你是對的,這是嘗試很多很多解決方案後複製錯誤。我知道json的內容類型。 Thx發現這個錯誤。但即使解決此問題,代碼也不能正常工作 – middelpat

+0

「瀏覽器不會下載該文件。」 - 告訴我們它所做的事情以及它所做的事情。 – Quentin

回答

0

只需返回文件結果與應用程序/八位字節中介類型。無需編寫內容處置標題。

return File(Encoding.UTF8.GetBytes(jsonString), 
      System.Net.Mime.MediaTypeNames.Application.Octet, 
      fileName); 
+0

Tnx for the quick awnser。但不幸的是這不起作用。我仍然堅持相同的行爲 – middelpat

+0

看到你的編輯,你提到它是一個Ajax.ActionLink。爲什麼ajax鏈接?只需使用指向GenerateOcJson視圖的常規超鏈接即可。既然你想讓用戶下載json文件,那就是你所需要的。例如:'@ Html.ActionLink(「Generate JSON」,「GenerateOcJson」)' – Johann

+0

使用Ajax,因爲我嘗試使用POST而不是GET – middelpat

0

使用通用MIME類型application/octet-stream。然後瀏覽器將數據視爲文件在本地下載。

+0

Tnx用於快速揚聲器。但不幸的是這不起作用。我仍然堅持以相同的行爲 – middelpat

+0

+1來計數不當的downvote,因爲這是與System.Net.Mime.MediaTypeNames.Application.Octet相同的字符串,爲您的答案提供 –

1

嘗試是這樣的(設置MIME類型爲純文本)和正常@Html.ActionLink

public ActionResult GenerateOcJson() 
{ 
var document = new { Data = jsonString, ContentType = "text/plain", FileName = String.Format("JSONResults_{0}.json", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")) };//... get from service layer 
    var cd = new System.Net.Mime.ContentDisposition 
    { 
     FileName = document.FileName, 
     // Inline = false means always prompt the user for downloading. 
     // Set it to true if you want the browser to try to show the file inline (fallback is download prompt) 
     Inline = false, 
    }; 
    Response.AppendHeader("Content-Disposition", cd.ToString()); 
    return File(document.Data, document.ContentType); 
} 
+0

Tnx。我想你是指ActionResult而不是ActionLink。但這不適合我。我沒有檔案,所以沒有路徑。我想下載的只是內存中的一個字符串。 @ johann的答案適合我。 thnx努力! – middelpat

+0

是的,我的意思是ActionResult。而我的確在沒有文件的情況下工作。它使用'jsonData'字符串,僅僅爲下載指定一個文件名。如果你嘗試它,你會發現這實際上是一個正確的答案!正如約翰的,我相信:-) –

+0

我相信在我身邊的一些代碼修改這個答案將工作得很好,因此我upvoted這個答案 – middelpat

相關問題