2017-02-23 61 views
1

MVC部分从MVC控制器返回excel文件和从angularJS下载它在POST请求

返回文件(流, “应用程序/ 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

+0

你得到的base64字符串作为HTTP调用 –

+0

什么错误讯息的结果你得到了吗? – georgeawg

回答

0

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; 
    } 

角位指示方法

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) { 

    });