如何下载zip文件

时间:2015-05-11 00:36:09

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

我正在尝试从我的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;
        }
    }

更新 pic

3 个答案:

答案 0 :(得分:15)

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

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

试试这个:

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

请查看this answer了解详情。

答案 1 :(得分:3)

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

答案 2 :(得分:0)

下面的代码对我来说可以正常工作,用于下载zip文件

控制器

const [goAway, setGoAway] = useState("");


 const browserTabcloseHandler = e => {
   e.preventDefault(); // If you prevent default behavior in Mozilla Firefox prompt will always be shown
   // Chrome requires returnValue to be set
   e.returnValue = "";
 };

 useEffect(() => {
   if (window) {
     Router.beforePopState(() => {
       //if (componentShouldBeSavedAsDraft(componentData)) {
       const result = window.confirm("are you sure you want to leave?");
       if (!result) {
         window.history.pushState("/", "");
         Router.push("/marketplace/upload-component");
       }
       console.log(goAway); // this value is always "" even though set differently in code. 
       return result;
     });
     window.onbeforeunload = browserTabcloseHandler;
   }
   //Router.events.on("routeChangeStart", handleRouteChange);

   return () => {
     if (window) {
       window.onbeforeunload = null;
     }
     Router.beforePopState(() => {
       return true;
     });
   };
 }, []);

服务

<?php
include ("conn.php");
     if(isset($_POST["export"]))
 {
    $connect = mysqli_connect("localhost", "root", "", "cruddatabase");  
    header('Content-Type: text/csv; charset=utf-8');  
    header('Content-Disposition: attachment; filename=data.csv');  
    $output = fopen("php://output", "w");  
    fputcsv($output, array('ID Company Name','Company Type','Name','Email','Contact Number','Anniversary Date','Organisation Name','Meeting','Timeline For Conversation','Currency','Card','Locations'));  
    $query = "SELECT * FROM crudtable WHERE adate >= '$fdate' AND adate <= '$tdate' ORDER BY adate DESC";  
    $result = mysqli_query($con, $query);  
    while($row = mysqli_fetch_assoc($result))  
    {  
         fputcsv($output, $row);  
    }  
    fclose($output);  
}  
 ?>
相关问题