最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to download ByteArrayContent of HttpResponseMessage as zip - Stack Overflow

programmeradmin4浏览0评论

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

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

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

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

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

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

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

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

Share Improve this question edited Feb 16, 2015 at 8:43 freethinker asked Feb 16, 2015 at 8:29 freethinkerfreethinker 2,4354 gold badges28 silver badges56 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

I found the solution:

Server:

1.Convert byte array to base64 string:

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

2.result Content is StringContent instead of ByteArrayContent:

result.Content = new StringContent(base64String);

Client:

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

below is the function code which I use to download files of any type

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

and its server side code

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

you can replace excel part with zip part and done...

发布评论

评论列表(0)

  1. 暂无评论