首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何下载zip文件

如何下载zip文件
EN

Stack Overflow用户
提问于 2015-05-11 08:36:09
回答 3查看 26.7K关注 0票数 23

我正在尝试从我的web api控制器下载zip文件。它正在返回文件,但当我尝试打开时,我收到一条消息,该zipfile无效。我看过其他关于这方面的帖子,回复是添加了responseType:'arraybuffer‘。对我还是不起作用。我在控制台中也没有收到任何错误。

代码语言:javascript
复制
  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控制器

代码语言:javascript
复制
 [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;
        }
    }

更新

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-05-14 13:45:00

我认为您在错误的位置设置了responseType,而不是这样:

代码语言:javascript
复制
$http.post('/api/apiZipPipeLine/', model)

试试这个:

代码语言:javascript
复制
$http.post('/api/apiZipPipeLine/', model, {responseType:'arraybuffer'})

有关更多详细信息,请查看this answer

票数 18
EN

Stack Overflow用户

发布于 2016-03-12 14:18:08

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

代码语言:javascript
复制
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();
票数 4
EN

Stack Overflow用户

发布于 2020-03-16 15:03:53

下面的代码对我来说下载zip文件很好,

控制器

代码语言:javascript
复制
$scope.downloadExport = function (id,filename,frmdata) {
         frmdata = {};
        var data = tdioServices.downloadexport(id,filename,frmdata);
         data.success(function(success) {
                var blob = new Blob([success], { type:"arraybuffer" });           
                var downloadLink = angular.element('<a></a>');
                downloadLink.attr('href',window.URL.createObjectURL(blob));
                downloadLink.attr('download', filename);
                downloadLink[0].click();
                $COMMON_ACCEPT = "Download Successfully";
                $COMMON_ACCEPT_TEXT = "Success";
                toastr.success($COMMON_ACCEPT, $COMMON_ACCEPT_TEXT);

        });
    };

服务

代码语言:javascript
复制
 this.downloadexport = function(id,filename,frmdata){
       var request = $http({method:'get', url:APP_URL+'/exports/'+id+'/download/'+filename, data:frmdata,responseType:'arraybuffer'});
       return request;        
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30158115

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档