【问题标题】:How download a byte array (byte[]) from web API (.Net) with Angular JS如何使用 Angular JS 从 Web API (.Net) 下载字节数组 (byte[])
【发布时间】: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


    【解决方案1】:

    嗯,我已经解决了这个问题,我想分享解决方案。

    核心问题在于web-api和表现层,那么我们需要在这里修改代码:

    Api Controller上,将字节数组转换为base64上的字符串并发送http响应内容

    [HttpGet]
    [AuthorizeWebApi]
    [Route("downloadZip")]
    public async Task<IHttpActionResult> downloadZipFile(){
        try{
        //Using WS reference
            using(ServiceLayer services = new ServiceLayer()){
    
            //Catch the byte array
            arr = services.getByteArray();
    
            //Encode in base64 string
            string base64String = System.Convert.ToBase64String(arr, 0, arr.length);    
    
            //Build the http response       
                var result = new HttpResponseMensage(HttpStatusCode.OK){
                    Content = new StringContent(base64String); }
    
                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 Controller 上,不转换 Blob 上的数据响应,定义有关数据响应和下载的元数据:

    $scope.DonwloadZip = function(){
    $http.get('api/myControllerUrlBase/downloadZip')
        .success(function(data, status, headers, config){
                if(status === true && data != null){
    
                    //No convert data on Blob
                    var fileURL = 'data:application/octec-stream;charset=utf-8;base64,'+ data;
                    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
        });
    }
    

    请记住,如果您使用的是 Angular 1.6.5 或更高版本,http 请求必须类似于:

       $http({
          method: 'GET',
          url: 'api/myControllerUrlBase/downloadZip'
       }).then(function (response){
           //Success
       },function (error){
           //Error
       });
    

    我希望这对某人有用,谢谢你的帮助!

    【讨论】:

      猜你喜欢
      • 2021-09-05
      • 2014-11-18
      • 2013-12-16
      • 2016-01-08
      • 1970-01-01
      • 2019-12-11
      • 1970-01-01
      • 2021-06-13
      相关资源
      最近更新 更多