【发布时间】:2018-12-11 23:03:12
【问题描述】:
我正在与 SOA 架构师一起研究解决方案,但在将 .zip 文件转换为 WS 层上的字节数组并通过 Web API 从表示层下载时遇到问题。
zip 文件下载成功,但无法解压缩文件。 让我用代码解释一下:
业务层
在业务层上,我们定义了一种方法,可以将文件 zip 转换为字节数组
//This method is defined on business layer and exposed on WS in WCF Layer
//Class: BusinessLayer
public byte[] convertingZip(){
try{
pathFile = "directoryOnServer/myZipFile.zip"
byte[] arr = File.ReadAllBytes(pathFile);
return arr;
}catch(Exception ex){ /*Do something*/ }
}
WCF 服务层
在WCF 服务层,我们编写了一个返回数组字节的方法并将其公开
//Class: ServiceLayer
public byte[] getByteArray(){
try{
BusinessLayer blObject = new BusinessLayer();
return blObject.convertingZip();
}catch(Exception ex){ /*Do something*/ }
}
网络 API
在Web API 项目上,我们编写了一个使用 WCF 服务层并将字节数组返回到内容中的方法
//This controller must be return the zip file
[HttpGet]
[AuthorizeWebApi]
[Route("downloadZip")]
public async Task<IHttpActionResult> downloadZipFile(){
try{
using(ServiceLayer services = new ServiceLayer()){
arr = services.getByteArray();
var result = new HttpResponseMensage(HttpStatusCode.OK){
Content = new ByteArrayContent(arr); }
result.Content.Headers.ContentDisposition
= new ContentDispostionHeaderValue("attachment"){
FileName = "zip-dowload.zip" };
result.Content.Headers.ContentType
= new MediaTypeHeaderValue("application/octec-stream");
var response = ResponseMessage(result);
return result;
}
}cacth(Exception ex){ /*Do something*/ }
}
表示层
在表示层我用angular JS 1.6.5下载文件
//On Web App project consume the WebApi with Angular
//MyController.js
$scope.DonwloadZip = function(){
$http.get('api/myControllerUrlBase/downloadZip')
.success(function(data, status, headers, config){
if(status === true && data != null){
var file = new Blob([data], {type: "application/zip"});
var fileURL = URL.createObjectUrl(file);
var a = document.createElement(a);
a.href = fileURL;
a.target = "_blank";
a.download = "MyZipFileName.zip";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}else { /*Do something */}
})
.error(function(data, status, headers, config) {
//show error message
});
}
我不确定这样做是否正确。我用 .xml、.txt 测试了一些类似的东西。和 .csv 文件和作品。但不要使用 zip 文件。
那么,将 zip 文件转换为字节数组并从 Web 应用项目获取我的 Web API 的正确方法是什么?
非常感谢您的帮助。
【问题讨论】:
标签: javascript c# asp.net .net asp.net-web-api