如何将 HttpResponseMessage 的 ByteArrayContent 下载为 zip

Ole*_*ich 1 javascript c# asp.net asp.net-web-api angularjs

我在客户端使用 Web Api (C#) 和 angular.js。我需要下载服务器响应内容(zip 的 ByteArrayContent)。我在服务器上有这个方法:

public HttpResponseMessage Download(DownloadImagesInput input)
        {
            if (!string.IsNullOrEmpty(input.ImageUrl))
            {
                byte[] imageBytes = GetByteArrayFromUrl(input.ImageUrl);

                ZipManager manager = new ZipManager();
                HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
                byte[] zipBytes;


                zipBytes = string.IsNullOrEmpty(input.QrCode) ? manager.ZipFiles(imageBytes) 
                                                              : manager.ZipFiles(imageBytes, input.QrCode);

                result.Content = new ByteArrayContent(zipBytes);


                result.Content.Headers.ContentType =
                                    new MediaTypeHeaderValue("application/zip");
                return result;

            }

            return new HttpResponseMessage(HttpStatusCode.InternalServerError);
        }
Run Code Online (Sandbox Code Playgroud)

ZipManager 是我的服务,它只返回 zip 文件的字节数组。我需要在客户端下载这个 zip 存档。这是我的客户:

$apiService.downloadZip({ 'ImageUrl': $scope.currentImage, 'QrCode': str }).then(function (response) {

            var hiddenElement = document.createElement('a');

            hiddenElement.href = 'data:application/zip,' + response.data;
            hiddenElement.target = '_blank';
            hiddenElement.download = 'images.zip';
            hiddenElement.click();
        });
Run Code Online (Sandbox Code Playgroud)

结果:下载 zip 文件但我无法打开它,文件格式无效

错误

在服务器上创建的 zip 文件没问题,我只是通过直接将他从服务器保存到磁盘来检查它...需要帮助。

Ole*_*ich 5

我找到了解决方案:

服务器:

1.将字节数组转换为base64字符串:

string base64String = System.Convert.ToBase64String(zipBytes, 0, zipBytes.Length);
Run Code Online (Sandbox Code Playgroud)

2.result Content 是 StringContent 而不是 ByteArrayContent:

result.Content = new StringContent(base64String);
Run Code Online (Sandbox Code Playgroud)

客户:

$apiService.downloadZip({ 'ImageUrl': $scope.currentImage, 'QrCode': str }).then(function (response) {
            var hiddenElement = document.createElement('a');

            hiddenElement.href = 'data:application/octet-stream;charset=utf-8;base64,' + response.data;
            hiddenElement.target = '_blank';
            hiddenElement.download = 'images.zip';
            hiddenElement.click();
        });
Run Code Online (Sandbox Code Playgroud)