简体   繁体   中英

Returning a zip file to angularjs for download

I have the following angularjs code:

$scope.search = function() {
    creatorService.search($scope.model).then(function(data) {
        saveAs(new Blob([data], { type: "application/octet-stream'" }), 'testfile.zip');
    });
};

(which also uses fileSaver.js )

And then the following method on my webapi2 side:

public HttpResponseMessage Post(Object parameters)
    {
        var streamContent = new PushStreamContent((outputStream, httpContext, transportContent) =>
           {
               try
               {
                   using (var zip = new ZipFile())
                   {
                       zip.AddEntry("test.txt", "test data");
                       zip.Save(outputStream);
                   }
               }
               finally
               {
                   outputStream.Close();
               }
           });
        streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
        streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = "test.zip"
        };

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

        return response;
    }

I got a lot of this from this post , and it uses ZipFile.

Everything seems to be working just perfect, except that when I download the zip file, I can't open it- it is invalid. It has the right size, and appears to have the right content, but I just can't open it.

I can verify that the angularjs code is hitting Post() correctly, parameters are being passed (if I have them) and that the Post() is executing and returning without error. The return content is then properly processed by the fileSaver stuff, and I can save the resulting zip file.

Am I not doing this the right way, or am I doing something wrong?

I'm reposting my comment (because it was the solution) :

If you call directly (without using any javascript code) your service, do you get a valid zip file ? I suspect the ajax call to corrupt your file. What is the type of data in your js code ?

If this is a string, your browser is maybe applying an utf8 conversion (corrupting your file). In that case, you can ask for an ArrayBuffer when doing your ajax request wih xhr.responseType = "arraybuffer";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM