2016-03-08 54 views
0

我環顧四周,很多人似乎都有同樣的問題,被下載的文件已損壞。我在前端使用web api 2和angular。使用AngularJS從Asp.net Web API 2下載Excel

服務器端

[Route("api/export/{id}")] 
    public async Task<IHttpActionResult> GetFileAsync(Guid id) 
    {   
     var originalFile = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/template.xls"); 

     var stream = _exportService.Export(id, originalFile); 

     return new FileActionResult(stream); 
    } 


public class FileActionResult : IHttpActionResult 
{ 
    private Stream Data { get; } 

    public FileActionResult(Stream data) 
    { 
     Data = data; 
    } 

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) 
    { 
     HttpResponseMessage response = new HttpResponseMessage 
     { 
      Content = new StreamContent(Data) 
     }; 
     //response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); 
     //response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ms-excel"); 
     //response.Content.Headers.ContentDisposition.FileName = "ExportedCOBie.xls"; 
     response.Content.Headers.ContentLength = Data.Length; 

     return Task.FromResult(response); 
    } 
} 

角客戶

   function(Restangular, FileSaver, Blob) { 

      this.exportToCobie = function(projectId) { 
       toastr.info('Exporting data', 'Info'); 
       Restangular.one("export/" + projectId) 
        .get({ responseType: "arraybuffer" }) 
        .then(function (data) {       
         var file = new Blob([data], { type: 'application/vnd.ms-excel' }); 
         FileSaver.saveAs(file, 'export.xls');     
       }) 
      }     
     } 

任何幫助將非常感激,感謝。


public MemoryStream Export(Guid projectId, string file) 
    { 
     try 
     { 
      var fileStream = new FileStream(file, FileMode.Open); 
      _workbook = new HSSFWorkbook(fileStream); 
      fileStream.Close(); 

      var contacts = _uow.ContactRepository.FindAllBy(c => c.ProjectId == projectId); 
      //var fileOutputStream = new FileStream(file, FileMode.Create); 
      var memoryStream = new MemoryStream(); 
      _workbook.Write(memoryStream); 
      memoryStream.Position = 0; 
      return memoryStream; 
     } 
     catch (Exception exception) 
     { 
      _logger.Error(exception.Message); 
     } 
     return null; 
    } 
+0

您下載的文件是否有內容,但它只是損壞,或者它是0字節? –

+0

@RonBrogan它有內容但已損壞,怪異的字符。 –

+0

您可以發佈這裏發生了什麼:'_exportService.Export' –

回答

0

下面的代碼做了魔術,如果其他人做與Restangular相同,希望它有幫助!

(function() { 
    'use strict'; 
    angular 
     .module('app.cobie.export') 
     .service('CobieExportDataService', ['Restangular', 'FileSaver', 'Blob', 
      function (Restangular, FileSaver, Blob) { 

       this.exportToCobie = function (projectId) { 
        toastr.info('Exporting COBie data', 'Info'); 
        return Restangular.withConfig(function(RestangularConfigurer) { 
         RestangularConfigurer.setDefaultHttpFields({ 
          cache : false , 
          responseType: "arraybuffer",  
         }); 
        }).one("export/" + projectId).get().then(function (res) {       
         var data = new Blob([res], { type: 'application/vnd.ms-excel' }); 
         FileSaver.saveAs(data, 'export.xls'); 
        }) 
       } 

      }]); 
})(); 
0

我試圖下載一個PDF文件時有同樣的問題。我不能確切地記得問題是什麼,但這裏是我的工作成功回調:

function success(res) { 

    var file = new Blob([res.data], { type: 'application/pdf' }); 
    var fileName = 'somefilename' + moment().format('YYYYMMDDTHHmm') + '.pdf'; 

    if ($window.navigator && $window.navigator.msSaveOrOpenBlob) { 
     $window.navigator.msSaveOrOpenBlob(file, fileName); 
    } else { 
     var a = document.createElement('a'); 
     a.href = URL.createObjectURL(file); 
     a.target = '_blank'; 
     a.download = fileName; 
     document.body.appendChild(a); 
     a.click(); 
    } 
} 

希望它有幫助。

+0

不,輸出仍然損壞 –