javascript - 如何将 HttpResponseMessage 的 ByteArrayContent 下载为 zip

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

我在客户端使用 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);
        }

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

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

error

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

最佳答案

我找到了解决方案:

服务器:

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

string base64String = System.Convert.ToBase64String(zipBytes, 0, zipBytes.Length);

2.结果内容是StringContent而不是ByteArrayContent:

result.Content = new StringContent(base64String);

客户:

$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();
        });

关于javascript - 如何将 HttpResponseMessage 的 ByteArrayContent 下载为 zip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28537278/

相关文章:

javascript - jQuery 获取当前元素 (x)html

php - 集成 PayPal 快速结帐的更简单方法?

c# - 不向 Web 服务发送数据

c# - 在单例范围内注入(inject) Memoize 实例

.net - 我应该使用 ASP :Label tag?

asp.net - 在sql中编写分组查询(MS-Access)

javascript - 手动调用 jQuery document.ready 函数

javascript - Webstorm Angularjs插件不起作用,无法检测 'angular'关键字

C#:循环查找函数的最小值

asp.net - 在 IIS 中,为什么窗口身份验证没有显示为我的 Web 应用程序的选项之一?