How to download ByteArrayContent of HttpResponseMessage as zip

强颜欢笑 提交于 2021-02-08 11:36:51

问题


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

error

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


回答1:


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



回答2:


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...



来源:https://stackoverflow.com/questions/28537278/how-to-download-bytearraycontent-of-httpresponsemessage-as-zip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!