我在客户端使用 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 文件,但无法打开它,文件格式无效
服务器上创建的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/