【问题标题】:Get Excel file from HttpResponseMessage从 HttpResponseMessage 获取 Excel 文件
【发布时间】:2017-12-17 04:25:59
【问题描述】:

我正在处理一个 ASP.NET Core 2.2 项目,我需要使用浏览器下载我的 Excel,但是当我执行我的请求时,我只得到了一些 Json。

我的 Excel 在流中,流不为空!

这是我的代码:

HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.OK);
            var streamContent = new StreamContent(stream);

            streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            streamContent.Headers.ContentDisposition.FileName = "Excel.xlsx";

            message.Content = streamContent;

            return message;

这是我得到的回复:

{"version":{"major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1},"content":{"headers":[{"key":"Content-Type","value":["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]},{"key":"Content-Disposition","value":["attachment; filename=Excel.xlsx"]}]},"statusCode":200,"reasonPhrase":"OK","headers":[],"requestMessage":null,"isSuccessStatusCode":true}

那么,有人知道我如何使用 HttpResponseMessage 发送我的 Excel 文件吗?

我可以使用 Filesteam 下载我的 excel 文件,但我不想使用这种方式,因为我无法收到任何 Http 错误消息(错误请求、内部等) 但是,如果有人知道我如何发送这样的消息并返回 Filestream,我将很高兴阅读您的建议!

编辑:这是我返回 FileStreamResult 时的代码

                return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

【问题讨论】:

  • 那个excel文件在哪里?
  • 我的文件在我的项目创建的流上!

标签: c# asp.net excel asp.net-core


【解决方案1】:

您可以从 Stream 中读取为 Byte 数组,并返回 FileContentResult。

using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace DemoWebCore.Controllers
{
    [Route("api/[controller]")]
    public class FilesController : Controller
    {
        // GET api/files/sample.png
        [HttpGet("{fileName}")]
        public async Task<ActionResult> Get(string fileName)
        {
            var cd = new System.Net.Http.Headers.ContentDispositionHeaderValue("inline")
            {
                FileName = "Excel.xlsx"
            };
            Response.Headers.Add("Content-Disposition", cd.ToString());
            StreamContent stream = YOUR_STREAM_SOURCE
            byte[] content = await stream.ReadAsByteArrayAsync();
            return File(content, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        }
    }
}

【讨论】:

  • 嗨!感谢您的帮助,我只需要像您的示例一样返回 ActionResult 而不是 FileStreamResult,现在一切正常!
猜你喜欢
  • 2016-12-02
  • 2023-03-08
  • 2019-02-21
  • 2013-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多