尝试使用AngularJs和c#webapi从服务器下载zip文件

时间:2017-05-04 05:37:21

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

我知道有相似标题的帖子存在,但它对我来说并不适用于我如何实现这一目标:

的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时出现此问题。 enter image description here

4 个答案:

答案 0 :(得分:1)

zip.AddFile(&#34; SRC&#34);然后zip.Save(&#34; src&#34;); ?这没有意义。

你正在扯淡&#39; src&#39;目标名称&#39; src&#39;。为zip文件尝试另一个名称。

zip.Save("target")

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

尝试设置:

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

我通过设置类型responseType

来解决它
{ type: "application/octet-stream", responseType: 'arraybuffer' }

和我的apiService中的相同内容

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

答案 3 :(得分:0)

这可以通过使用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');
            });
        }