WebAPI和角度JS Excel文件下载 - 文件已损坏

tri*_*tri 9 c# rest excel asp.net-web-api angularjs

我正在我的WebAPI中生成一个Excel文件.我将它"存储"在一个内存流中,然后将响应输入如下:

var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(ms) };

            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = projectName + ".xlsx"
            };
           // ms.Close();
            return result;
Run Code Online (Sandbox Code Playgroud)

看起来服务器端工作正常.如果我将该内存流写入文件流,则会创建该文件,并且可以毫无问题地打开该文件.

在角度方面,如何在单击按钮时重新创建文件?

我试过这样的事情:

$scope.exportQuotas = function (projectName) {
    homeService.GetQuotas(projectName, $routeParams.token, $scope.selection).then(
             function (data) {
                 var dataUrl = 'data:application/octet-stream;' + data
                 var link = document.createElement('a');
                 angular.element(link)
                   .attr('href', dataUrl)
                   .attr('download', "bl.xlsx")
                   .attr('target', '_blank')
                 link.click();
             })
}
Run Code Online (Sandbox Code Playgroud)

该文件已创建但当我尝试打开它时,它已损坏...我已尝试将数据类型更改为vnd.ms-excel in angular但它不起作用...我怎样才能获得该文件点击下载?

编辑 Jorg回答后,我尝试了以下内容:api返回的是:

Status Code: 200
Pragma: no-cache
Date: Tue, 02 Sep 2014 02:00:24 GMT
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Type: application/binary
Access-Control-Allow-Origin: *
Cache-Control: no-cache
X-SourceFiles: =?UTF-8?B?        QzpcVXNlcnNcdHJpaGFuaC5waGFtXFByb2plY3RzXFF1b3RhUXVlcnlcUXVvdGFRdWVyeUFQSVxhcGlccXVvdGFcR2V0?=
Content-Disposition: attachment; filename=O14Y0129AUG.xlsx
Content-Length: 13347
Expires: -1
Run Code Online (Sandbox Code Playgroud)

从我所看到的,它看起来是正确的.

在客户端:

                 var file = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;' });
                 var fileURL = URL.createObjectURL(file);
                 window.open(fileURL);
Run Code Online (Sandbox Code Playgroud)

创建了一个excel文件,但它仍然已损坏...

谢谢

dan*_*iel 17

我有同样的问题.该文件在服务器端是正常的,但下载后它变得腐败.

为我解决的是添加responseType: "arraybuffer"到服务器请求.

然后在调用此行时var file = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;' }); ,data变量应该是类型ArrayBuffer,而不是字符串.

  • @ Shivam657这是你向你的请求添加响应类型的方式:`$ http.get(url,{responseType:"arraybuffer"})` (3认同)
  • 使用缓存为我工作:false,responseType:"arraybuffer", (3认同)
  • 您能否提供关于如何在服务器请求中添加responseType:"arraybuffer"的完整代码? (2认同)