[英]Returning a zip file to angularjs for download
I have the following angularjs code: 我有以下angularjs代码:
$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 ) (也使用fileSaver.js )
And then the following method on my webapi2 side: 然后在我的webapi2端使用以下方法:
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. 我从这篇文章中得到了很多,它使用了ZipFile。
Everything seems to be working just perfect, except that when I download the zip file, I can't open it- it is invalid. 一切似乎都工作得非常完美,除了下载zip文件时无法打开它-这是无效的。 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. 我可以验证angularjs代码是否正确命中了
Post()
,是否正在传递参数(如果有),并且Post()
正在执行并返回而没有错误。 The return content is then properly processed by the fileSaver stuff, and I can save the resulting zip file. 然后,由fileSaver东西正确处理返回的内容,然后我可以保存生成的zip文件。
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 ? 如果您直接致电(不使用任何JavaScript代码)服务,您会获得有效的zip文件吗? I suspect the ajax call to corrupt your file.
我怀疑ajax调用会损坏您的文件。 What is the type of data in your js code ?
您的js代码中的数据类型是什么?
If this is a string, your browser is maybe applying an utf8 conversion (corrupting your file). 如果这是字符串,则您的浏览器可能正在应用utf8转换(损坏了文件)。 In that case, you can ask for an ArrayBuffer when doing your ajax request wih
xhr.responseType = "arraybuffer";
在这种情况下,您可以在执行ajax请求时要求ArrayBuffer,即
xhr.responseType = "arraybuffer";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.