23

I am trying to download a zip file from my web api controller. It is returning the file but I am getting a message the zipfile is invalid when i try to open. I have seen other posts about this and the response was adding the responseType: 'arraybuffer'. Still isn't working for me. I'm not getting any errors in the console either.

  var model = $scope.selection;
    var res = $http.post('/api/apiZipPipeLine/', model)

    res.success(function (response, status, headers, config) {
        saveAs(new Blob([response], { type: "application/octet-stream", responseType: 'arraybuffer' }), 'reports.zip');
            notificationFactory.success();
    });

api controller

 [HttpPost]
    [ActionName("ZipFileAction")]
    public HttpResponseMessage ZipFiles([FromBody]int[] id)
    {
        if (id == null)
        {//Required IDs were not provided
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
        }

        List<Document> documents = new List<Document>();
        using (var context = new ApplicationDbContext())
        {
            foreach (int NextDocument in id)
            {
                Document document = context.Documents.Find(NextDocument);

                if (document == null)
                {
                    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
                }

                documents.Add(document);
            }
            var streamContent = new PushStreamContent((outputStream, httpContext, transportContent) =>
            {
                try
                {
                    using (var zipFile = new ZipFile())
                    {
                        foreach (var d in documents)
                        {
                            var dt = d.DocumentDate.ToString("y").Replace('/', '-').Replace(':', '-');
                            string fileName = String.Format("{0}-{1}-{2}.pdf", dt, d.PipeName, d.LocationAb);
                            zipFile.AddEntry(fileName, d.DocumentUrl);
                        }
                        zipFile.Save(outputStream); //Null Reference Exception
                    }
                }

                finally
                {
                    outputStream.Close();
                }
            });
            streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            streamContent.Headers.ContentDisposition.FileName = "reports.zip";

            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = streamContent
            };
            return response;
        }
    }

Update pic

Foreever
  • 7,099
  • 8
  • 53
  • 55
texas697
  • 5,609
  • 16
  • 65
  • 131

3 Answers3

18

I think you're setting the responseType in the wrong place, instead of this:

$http.post('/api/apiZipPipeLine/', model)

Try this:

$http.post('/api/apiZipPipeLine/', model, {responseType:'arraybuffer'})

Take a look at this answer for more details.

Community
  • 1
  • 1
Buddy
  • 10,874
  • 5
  • 41
  • 58
  • that did work! however the pdf's are corrupt? do I need to change something in my api controller? – texas697 May 14 '15 at 10:15
  • i posted a screenshot of a exception in my api. I know this might be a separate question but if you if you could take a look i would appreciate it – texas697 May 14 '15 at 10:36
  • Looks like get_Length() isn't supported, perhaps you need to download the entire stream first? – Buddy May 14 '15 at 15:46
4

At a matter of fact you are rigth adding responseType:'arraybuffer'. That added to the following code when received the response from ajax will prompt a file to download:

var a = document.createElement('a');
var blob = new Blob([responseData], {'type':"application/octet-stream"});
a.href = URL.createObjectURL(blob);
a.download = "filename.zip";
a.click();
0

Below code is working fine for me for download zip file,

Controller

$scope.downloadExport = function (id,filename,frmdata) {
         frmdata = {};
        var data = tdioServices.downloadexport(id,filename,frmdata);
         data.success(function(success) {
                var blob = new Blob([success], { type:"arraybuffer" });           
                var downloadLink = angular.element('<a></a>');
                downloadLink.attr('href',window.URL.createObjectURL(blob));
                downloadLink.attr('download', filename);
                downloadLink[0].click();
                $COMMON_ACCEPT = "Download Successfully";
                $COMMON_ACCEPT_TEXT = "Success";
                toastr.success($COMMON_ACCEPT, $COMMON_ACCEPT_TEXT);

        });
    };

Services

 this.downloadexport = function(id,filename,frmdata){
       var request = $http({method:'get', url:APP_URL+'/exports/'+id+'/download/'+filename, data:frmdata,responseType:'arraybuffer'});
       return request;        
    }
HEMAL
  • 420
  • 3
  • 14