【问题标题】:how to download a zip file如何下载 zip 文件
【发布时间】:2015-07-21 09:26:34
【问题描述】:

我正在尝试从我的 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 控制器

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

更新

【问题讨论】:

  • saveAs 函数中有什么?
  • 这是一个filesaver.js方法

标签: angularjs asp.net-web-api httpresponse zipfile pushstreamcontent


【解决方案1】:

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

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

试试这个:

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

查看this answer了解更多详情。

【讨论】:

  • 确实有效!但是pdf文件已损坏?我需要更改我的 api 控制器中的某些内容吗?
  • 我在我的 api 中发布了一个异常截图。我知道这可能是一个单独的问题,但如果你能看一下,我会很感激
  • 好像不支持get_Length(),可能需要先下载整个流?
【解决方案2】:

事实上,您添加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();

【讨论】:

    【解决方案3】:

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

    控制器

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

    服务

     this.downloadexport = function(id,filename,frmdata){
           var request = $http({method:'get', url:APP_URL+'/exports/'+id+'/download/'+filename, data:frmdata,responseType:'arraybuffer'});
           return request;        
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-20
      • 2023-03-16
      • 2017-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多