如何使用angular下载zip文件

时间:2021-12-19 09:56:52

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.

我想从我的web api控制器下载一个zip文件。它正在返回文件但我收到一条消息,当我尝试打开时,zipfile无效。我已经看过其他关于此的帖子,响应是添加了responseType:'arraybuffer'。仍然不适合我。我也没有在控制台中出现任何错误。

  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

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

Update 如何使用angular下载zip文件

更新

2 个解决方案

#1


15  

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

我认为你将responseType设置在错误的位置,而不是:

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

Try this:

尝试这个:

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

Take a look at this answer for more details.

请查看此答案以获取更多详细信息。

#2


3  

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:

事实上,你正在添加responseType:'arraybuffer'。当收到来自ajax的响应时,添加到以下代码将提示下载文件:

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

#1


15  

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

我认为你将responseType设置在错误的位置,而不是:

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

Try this:

尝试这个:

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

Take a look at this answer for more details.

请查看此答案以获取更多详细信息。

#2


3  

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:

事实上,你正在添加responseType:'arraybuffer'。当收到来自ajax的响应时,添加到以下代码将提示下载文件:

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