0

I have looked around and many people seem to have the same issue, the file being downloaded is corrupt. I am using web api 2 and angular on the front end.

server side

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

angular client

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

Any help will be much appreciated, thanks.


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;
    }
6
  • Does your downloaded file have content, but it's just corrupt, or is it 0 bytes? Commented Mar 8, 2016 at 14:04
  • @RonBrogan It has content but corrupted, weird characters. Commented Mar 8, 2016 at 14:41
  • Could you post what's going on here: _exportService.Export Commented Mar 8, 2016 at 14:42
  • @RonBrogan Export is just business logic creating the spreadsheet. I have tested the _exportService.Export method through an MVC controller and it works perfectly. Commented Mar 8, 2016 at 14:46
  • In that case, the only thing that I could see it being is if your stream isn't at the appropriate position at some point and only part of the stream gets to where you want it. Commented Mar 8, 2016 at 14:48

2 Answers 2

1

The code below did the magic if anyone else doing the same with Restangular, hope it helps!

(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');
                    })
                }

            }]);
})();
Sign up to request clarification or add additional context in comments.

Comments

0

I had the same issue when trying to download a pdf. I cant exactly remember what the issue was, but here is my working success callback:

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

Hope it helps.

1 Comment

No, output is still corrupt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.