【问题标题】:Why in ASP.NET MVC I get JSON instead of FileDownload?为什么在 ASP.NET MVC 中我得到 JSON 而不是 FileDownload?
【发布时间】:2014-11-08 17:43:18
【问题描述】:

我希望能够从我的网站下载附件,(我需要让它在 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,我需要能够将附件作为文件下载到用户的计算机。 我怎样才能使它成为简单的文件下载?我做错了什么?

【问题讨论】:

    标签: javascript asp.net asp.net-mvc json


    【解决方案1】:

    尝试更改此行:

    var response = new FileContentResult(fileBytes, MediaTypeNames.Application.Octet);
    

    到:

    var response = new FileContentResult(fileBytes, "image/jpeg");
    

    【讨论】:

    • 我尝试按照您写的进行更改,但没有任何更改。 - 打开新窗口,我看到 {"FileContents":"/9j/4AAQSkZJRg...bla..bla..Afbs//Z","ContentType":"image/jpeg","FileDownloadName":"CoverBack.JPG "} 就在页面上..
    【解决方案2】:

    希望你已经尝试过 - Returning binary file from controller in ASP.NET Web API

    它说返回HttpResponseMessage并设置Content的响应=文件内容并设置标题内容类型。

    另外,我建议调查一下 - Download file from an ASP.NET Web API method using AngularJS

    上面说,你还需要设置Content.Headers.ContentDispositionContent.Headers.ContentDisposition.FileName

    【讨论】:

      【解决方案3】:

      希望这行得通。

          [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/*"));
      
          }
      

      或者如果你有文件扩展名,而不是 * in (image/*)。

      参考:MSDN

      【讨论】:

        猜你喜欢
        • 2019-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多