【问题标题】:Trying to download zip file from server using AngularJs and c# webapi尝试使用 AngularJs 和 c# webapi 从服务器下载 zip 文件
【发布时间】:2017-05-04 05:37:21
【问题描述】:

我知道存在类似标题的帖子,但它对我不起作用,因为我试图实现这一点:

WebAPI

public async Task<HttpResponseMessage> ExportAnalyticsData([FromODataUri] int siteId, [FromODataUri] string start, [FromODataUri] string end) {
    DateTime startDate = Date.Parse(start);
    DateTime endDate = Date.Parse(end);

    using (ZipFile zip = new ZipFile()) {
        using (var DailyLogLanguagesCsv = new CsvWriter(new StreamWriter("src"))) {
            var dailyLogLanguages = await _dbContext.AggregateDailyLogSiteObjectsByDates(siteId, startDate, endDate).ToListAsync();
            DailyLogLanguagesCsv.WriteRecords(dailyLogLanguages);
            zip.AddFile("src");
        }


        using (var DailyLogSiteObjectsCsv = new CsvWriter(new StreamWriter("src"))) {
            var dailyLogSiteObjects = await _dbContext.AggregateDailyLogSiteObjectsByDates(siteId, startDate, endDate).ToListAsync();
            DailyLogSiteObjectsCsv.WriteRecords(dailyLogSiteObjects);
            zip.AddFile("src");
        }

        zip.Save("src");
        HttpResponseMessage result = null;
        var localFilePath = HttpContext.Current.Server.MapPath("src");

        if (!File.Exists(localFilePath)) {
            result = Request.CreateResponse(HttpStatusCode.Gone);
        } else {
            // Serve the file to the client
            result = Request.CreateResponse(HttpStatusCode.OK);
            result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
            result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
            result.Content.Headers.ContentDisposition.FileName = "Analytics";
        }
        return result;
    }
}

AngularJs

$scope.exportData = function () {
    apiService.dailyLog.exportAnalyticsData($scope.siteId, $scope.startDate, $scope.finishDate).then(function (response) {
        debugger;
        var blob = new Blob([response.data], { type: "application/zip" });
        saveAs(blob, "analytics.zip");
    })
};

function saveAs(blob, fileName) {
    var url = window.URL.createObjectURL(blob);
    var doc = document.createElement("a");
    doc.href = url;
    doc.download = fileName;
    doc.click();
    window.URL.revokeObjectURL(url);
}

当我下载文件时,我会收到文件损坏的信息。只有当我返回 zip 文件时才会发生这种情况。它适用于csv

在@wannadream 提出建议并编辑我的代码之后

                else
            {
                // Serve the file to the client
                result = Request.CreateResponse(HttpStatusCode.OK);
                result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
                result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
                result.Content.Headers.ContentDisposition.FileName = "Analytics";
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            }

当我尝试打开下载的zip 时遇到这样的问题。

【问题讨论】:

    标签: javascript c# angularjs asp.net-web-api


    【解决方案1】:

    尝试通过普通浏览器访问 WebAPI 控制器操作,看看它下载的 ZIP 是否可以打开。如果不能,那么您的问题出在您的 WebAPI 上。

    【讨论】:

    • 如果我从服务器端将此文件保存在我的光盘上,我可以打开它
    • 尝试将“{ type: "application/zip" }" 设置为 "{ type: "application/octet-stream" }"
    【解决方案2】:

    zip.AddFile("src");然后 zip.Save("src"); ?这没有意义。

    您正在使用目标名称“src”压缩“src”。为 zip 文件尝试另一个名称。

    zip.Save("target")
    
    var localFilePath = HttpContext.Current.Server.MapPath("target");
    

    尝试设置:

    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    

    【讨论】:

    • 我有我自己的文件的 src 我只是不想显示它。我在返回单个 csv 文件时工作。但是,当我将它们全部压缩并返回时,我会得到文件已损坏的信息。
    • 从服务器端打开压缩文件。检查是否可以从服务器打开。
    • 如果我从服务器端将此文件保存在我的光盘上,我可以打开它
    • 好的,我稍后再试,因为我现在无法访问代码,会提供信息
    【解决方案3】:

    我通过设置类型 responseType 来解决它

    { type: "application/octet-stream", responseType: 'arraybuffer' }
    

    在我的 apiService 中也是一样的

    $http.get(serviceBase + path), {responseType:'arraybuffer'});
    

    【讨论】:

      【解决方案4】:

      这可以使用DotNetZip 来完成,并将响应类型设置为arraybuffer,检查下面的代码以获得完整的理解。

      1.WebApi控制器

              [HttpPost]
              [Route("GetContactFileLink")]
              public HttpResponseMessage GetContactFileLink([FromBody]JObject obj)
              {
                      string exportURL = "d:\\xxxx.text";//replace with your filepath
      
                      var fileName =  obj["filename"].ToObject<string>();
      
                      exportURL = exportURL+fileName;
      
                      var resullt = CreateZipFile(exportURL);
      
      
                      return resullt;
              }
      
      private HttpResponseMessage CreateZipFile(string directoryPath)
              {
                  try
                  {
                      HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
      
                      using (ZipFile zip = new ZipFile())
                      {
                          zip.AlternateEncodingUsage = ZipOption.AsNecessary;
                          zip.AddFile(directoryPath, "");
                          //Set the Name of Zip File.
                          string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
                          using (MemoryStream memoryStream = new MemoryStream())
                          {
                              //Save the Zip File to MemoryStream.
                              zip.Save(memoryStream);
      
                              //Set the Response Content.
                              response.Content = new ByteArrayContent(memoryStream.ToArray());
      
                              //Set the Response Content Length.
                              response.Content.Headers.ContentLength = memoryStream.ToArray().LongLength;
      
                              //Set the Content Disposition Header Value and FileName.
                              response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                              response.Content.Headers.ContentDisposition.FileName = zipName;
      
                              //Set the File Content Type.
                              response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
                              return response;
                          }
                      }
                  }
                  catch(Exception ex)
                  {
                      throw new ApplicationException("Invald file path or file not exsist");
                  }
              }
      

      2.Angular组件

          function getcontactFileLink(token, params) {
      
                      return $http.post('api/event/GetContactFileLink', params, { headers: { 'Authorization': 'Bearer ' + token, 'CultureCode': cc }, 'responseType': 'arraybuffer' }).then(response);
      
                      function response(response) {
                          return response;
                      }
                  }
      
      function showcontactfile(item) {
                  usSpinnerService.spin('spinner-1');
                  var params = {};
                  params.filename = item.filename;
                  EventListingProcess.getcontactFileLink(accessToken, params).then(function (result) {
                      var blob = new Blob([result.data], { type: "application/zip" });
                      var fileName = item.filename+".zip";
                      var a = document.createElement("a");
                      document.body.appendChild(a);
                      a.style = "display:none";
                      var url = window.URL.createObjectURL(blob);
                      a.href = url;
                      a.download = fileName;
                      a.click();
                      window.URL.revokeObjectURL(url);
                      a.remove();
      
      
                  }).catch(function (error) {
                      vm.message = frameworkFactory.decodeURI(error.statusText);
                      //frameworkFactory.translate(vm, 'message', error.statusText);
                  }).finally(function () {
                      usSpinnerService.stop('spinner-1');
                  });
              }
      

      【讨论】:

        猜你喜欢
        • 2016-10-01
        • 2023-03-31
        • 1970-01-01
        • 2019-12-12
        • 2017-01-24
        • 1970-01-01
        • 2018-09-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多