【问题标题】:download excel file using web api and angularjs使用 web api 和 angularjs 下载 excel 文件
【发布时间】:2021-02-13 14:10:08
【问题描述】:

前端

      var url = baseUrl+ "/api/Home/DownloadReport";
      window.open(url);

后端

     [HttpGet]

    public HttpResponseMessage DownloadReport()
    {
        var stream = new System.IO.MemoryStream(File.ReadAllBytes(@"C:\Users\mypc\Desktop\Test\5\WebApplication1\Report.xlsx"));
      HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ByteArrayContent(stream);
        };
        result.Content.Headers.ContentDisposition = new 
      System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
        {
            FileName = "myworkbook.xlsx"
        };
        result.Content.Headers.ContentType = new 
        System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
        result.Content.Headers.ContentLength = stream.Length;
        return result
         }

我正在尝试使用 web API 和 angularjs 下载一个 excel 文件,但是当我单击下载按钮时,它会打开一个新选项卡,其中包含如下消息但不下载文件有人可以向我建议代码有什么问题.

StatusCode:200,ReasonPhrase:'OK',Version:1.1,Content:System.Net.Http.ByteArrayContent,Headers:{Content-Type:application/octet-stream Content Disposition:attachment;filename=myworkbook.xlsx}

我知道之前有人问过这个问题,但尝试了很多解决方案,但都无法解决问题

【问题讨论】:

    标签: c# angularjs asp.net-web-api asp.net-web-api2


    【解决方案1】:

    前端

    不使用window.open,而是使用以下解决方法:

    var url = baseUrl+ "/api/Home/DownloadReport";
    
    var tmp = document.createElement('A');
    tmp.href = url;
    tmp.type = 'application/vnd.ms-excel';
    tmp.download = 'myworkbook.xlsx';
    tmp.click();
    

    后端

    尝试在MediaTypeHeaderValue构造函数的参数中使用application/vnd.ms-excel

    【讨论】:

    • 我尝试了上面建议的代码。但它显示错误,例如 myworkbook.xlsx 的文件格式和扩展名不匹配。文件可能已损坏或不安全。但服务器上的输入文件是好的.我也试图改变
    • 我也试过 application/vnd.openxmlformat-officedocument.spreadsheetml.sheet 但也没用
    • 尝试使用StreamContent 而不是ByteArrayContent
    • 谢谢。我通过将返回类型更改为 filereturn 解决了它,现在它正在工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 2018-02-01
    • 2014-07-27
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    相关资源
    最近更新 更多