从MVC控制器返回excel文件并在POST请求中从angularJS下载它

时间:2017-02-23 05:11:12

标签: javascript angularjs asp.net-mvc excel

MVC部分

return File(stream," application / vnd.ms-excel",file.FileName);

我以上述方式从MVC控制器返回文件。

AngularJS控制器

$scope.ExcelValidate = function () {
    if ($scope.files && $scope.files.length && $scope.selectedFileType != -1) {
        busyIndicatorService.showBusy("Uploading data...");
        for (var i = 0; i < $scope.files.length; i++) {
            var file = $scope.files[i];
            $scope.file = file.name;
            Upload.upload({
                url: '/MasterExcelImport/ValidateExcelData',
                fields: {
                    uploadType: $scope.selectedFileType.Key.Key
                },
                file: file
            }).progress(function (evt) {
                console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
                $scope.file.progress = parseInt(100.0 * evt.loaded / evt.total);
            }).success(function (data) {
                busyIndicatorService.stopBusy();
                var blob = new Blob([data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
                var objectUrl = URL.createObjectURL(blob);
                window.open(objectUrl);
            }).error(function (data, status, headers, config) {
                busyIndicatorService.stopBusy();
            });
        }
    }
};

返回文件已经到达成功部分。但下载部分失败了。

有人可以帮我解决这个问题吗?

谢谢, Erandika Sandaruwan

1 个答案:

答案 0 :(得分:1)

Mvc / WeApi控制器操作

 [HttpPost]
    public HttpResponseMessage DownloadExcelFile()
    {
        var stream = new MemoryStream();//fill stream from data or use filestream
        var result = Request.CreateResponse(HttpStatusCode.OK);
        result.Content = new ByteArrayContent(stream.ToArray());
        result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
        result.Content.Headers.ContentDisposition.FileName = "SystemPerformance.xlsx";
        return result;
    }

Angular Contoller方法

 ExampleService.DownloadExcelFile({}/*post data*/,/*success function*/ function (response) {
        var headers = response.headers();
        var blob = new Blob([response.data], { type: headers['content-type'] });
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = "excelfile.xlsx";
        link.click();
    }, /*error function*/ function (err) {

    });