16

Sto provando a scaricare un file zip dal mio controller web api. Sta restituendo il file, ma sto ricevendo un messaggio che zipfile non è valido quando provo ad aprire. Ho visto altri post su questo e la risposta è stata aggiungendo il responseType: 'arraybuffer'. Non funziona ancora per me. Neanche io ricevo errori nella console.come scaricare un file zip usando angolare

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

controller di api

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

Aggiornamento pic

+0

Cosa c'è nella funzione 'saveAs'? – miensol

+0

è un metodo filesaver.js – texas697

risposta

13

Penso che si sta impostando il responseType nel posto sbagliato, al posto di questo:

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

Prova questa:

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

Dai un'occhiata a this answer per maggiori dettagli.

+0

che ha funzionato! tuttavia i pdf sono corrotti? devo cambiare qualcosa nel mio controller api? – texas697

+0

ho postato uno screenshot di un'eccezione nella mia api. So che questa potrebbe essere una domanda a parte, ma se tu potessi dare un'occhiata lo apprezzerei – texas697

+0

Sembra che get_Length() non sia supportato, forse devi prima scaricare l'intero stream? – Buddy

3

In realtà si aggiunge responseType:'arraybuffer'. Quello aggiunto al seguente codice quando ricevuto la risposta da ajax richiederà il download di un file:

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(); 
Problemi correlati