[英]Long polling to asp.net mvc app requires POST instead of GET ajax method. Why?
[英]Why in ASP.NET MVC I get JSON instead of FileDownload?
我希望能夠從我的站點下載附件(我需要使其在IE中運行),因此在html中,我具有:
<a href="api/attachments/DownloaAttachment?id={{attachment.Id}}" target="_blank">
Download Image
</a>
<!-- {{attachment.Id}} - it's because I use AngularJS :) -->
在控制器中:
[HttpGet]
public FileContentResult DownloaAttachment(int id)
{
var att = GetAttachmentById(id);
byte[] fileBytes = att.Content.Content;
var response = new FileContentResult(fileBytes, MediaTypeNames.Application.Octet);
response.FileDownloadName = att.FileName;
return response;
}
但是當我單擊“下載圖像”時-我有一個新窗口,並從控制器以json響應,例如:
{"FileContents":"/9j/4.. some bytes..ZK9k=","ContentType":"application/octet-stream","FileDownloadName":"Cover.jpg"}
但是我不需要JSON,我需要能夠將附件作為文件下載到用戶的計算機。 如何將其簡化為簡單的文件下載? 我做錯了什么?
嘗試更改此行:
var response = new FileContentResult(fileBytes, MediaTypeNames.Application.Octet);
至:
var response = new FileContentResult(fileBytes, "image/jpeg");
希望您已經嘗試過- 從ASP.NET Web API中的控制器返回二進制文件 。
它說返回HttpResponseMessage
並設置響應的Content
=文件內容並設置標頭內容類型。
此外,我建議研究一下- 使用AngularJS從ASP.NET Web API方法下載文件 。
它說,您還需要設置Content.Headers.ContentDisposition
和Content.Headers.ContentDisposition.FileName
。
希望這行得通。
[HttpGet]
public HttpResponseMessage DownloaAttachment(int id)
{
var att = GetAttachmentById(id);
byte[] fileBytes = att.Content.Content;
var response = new FileContentResult(fileBytes, MediaTypeNames.Application.Octet);
response.FileDownloadName = att.FileName;
return Request.CreateResponse(HttpStatusCode.OK, response, new MediaTypeHeaderValue("image/*"));
}
或者如果您具有文件擴展名,而不是(image / *)中的*。
參考: MSDN
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.