本文介绍了如何以zip格式下载HttpResponseMessage的ByteArrayContent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I work with Web Api (C#) and angular.js on client.I need to download server response content (ByteArrayContent of zip).I have this method on server:

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存档.这是我的客户:

The ZipManager is my Service, it just return the byte array of zip file.I need to download this zip archive on client.This is my client:

$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文件,但我无法打开它,该文件的格式无效

Result : download zip file but i can't open it, the file have invalid format

在服务器上创建的zip文件是可以的,我只是通过直接将其从服务器保存到磁盘来进行检查...需要帮助.

The zip file created on server is ok, i just check it by directly save him from server to disk...Need help.

推荐答案

我找到了解决方法:

服务器:

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

1.Convert byte array to base64 string:

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

2.result内容是StringContent而不是ByteArrayContent:

2.result Content is StringContent instead of 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();
        });

这篇关于如何以zip格式下载HttpResponseMessage的ByteArrayContent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 07:43