Reputation: 5183
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?
Upvotes: 0
Views: 6395
Reputation: 4069
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";
Upvotes: 5