簡體   English   中英

嘗試使用AngularJs和C#WebAPI從服務器下載zip文件

[英]Trying to download zip file from server using AngularJs and c# webapi

我知道存在具有相似標題的帖子,但是它對我來說是不起作用的,我如何嘗試實現這一點:

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時遇到這樣的問題。 在此處輸入圖片說明

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");

嘗試通過普通的瀏覽器訪問WebAPI控制器操作,然后查看其下載的ZIP是否可以打開。 如果不能,那么您的問題出在您的WebAPI中。

我通過設置類型responseType來解決它

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

和我的apiService中的相同

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

這可以使用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.角組件

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM