如何下载HttpResponseMessage的ByteArrayContent作为zip

时间:2015-02-16 08:29:58

标签: 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文件是可以的,我只是直接将它从服务器保存到磁盘... 需要帮助。

2 个答案:

答案 0 :(得分:3)

我找到了解决方案:

服务器:

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

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

2.result内容是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();
        });

答案 1 :(得分:2)

下面是我用来下载任何类型文件的功能代码

var downloadFile = function (filename) {
    enableSpinner();
    var ifr = document.createElement('iframe');
    ifr.style.display = 'none';
    document.body.appendChild(ifr);
    ifr.src = document.location.pathname + "api/FileIo/Download?filename='" + escape(filename) + "'";
    ifr.onload = function () {
        document.body.removeChild(ifr);
        ifr = null;
    };
};

及其服务器端代码

[HttpGet]
        public HttpResponseMessage Download(string filename)
        {
            filename = filename.Replace("\\\\", "\\").Replace("'", "").Replace("\"", "");
            if (!char.IsLetter(filename[0]))
            {
                filename = filename.Substring(2);
            }

            var fileinfo = new FileInfo(filename);
            if (!fileinfo.Exists)
            {
                throw new FileNotFoundException(fileinfo.Name);
            }

            try
            {
                var excelData = File.ReadAllBytes(filename);
                var result = new HttpResponseMessage(HttpStatusCode.OK);
                var stream = new MemoryStream(excelData);
                result.Content = new StreamContent(stream);
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = fileinfo.Name
                };
                return result;
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.ExpectationFailed, ex);
            }
        }

你可以用zip部件替换excel部件并完成......