Angular与.NET Webapi 文件下载

Posted ningyouyou

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Angular与.NET Webapi 文件下载相关的知识,希望对你有一定的参考价值。

angular代码

        function download(method, url, params, data) 
            //$scope.excelinfo = ;
            var httpval = 
                method: method, //"POST",
                url: url, //"http://localhost:xxx/api/xxx/xxx/ExportExcelApply",
                responseType: "blob",
                headers: 
                    ‘Content-Type‘: ‘application/json; charset=UTF-8‘
                ,
                params: params,
                data: data //$scope.excelinfo
            ;
            $http(httpval).then(function (res) 
                var filename = res.headers("Content-Disposition").split(";")[1].split("filename=")[1];
                var fileNameUnicode = res.headers("Content-Disposition").split("filename*=")[1];
                if (fileNameUnicode)  //当存在 filename* 时,取filename* 并进行解码(为了解决中文乱码问题)
                    filename = decodeURIComponent(fileNameUnicode.split("‘‘")[1]);
                    //console.log(fileName);
                
                var blob = res.data;
                var success = false;
                try 
                    if (navigator.msSaveBlob)
                        navigator.msSaveBlob(blob, filename);
                    else 
                        // Try using other saveBlob implementations, if available
                        var saveBlob = navigator.webkitSaveBlob || navigator.mozSaveBlob || navigator.saveBlob;
                        if (saveBlob === undefined) throw "Not supported";
                        saveBlob(blob, filename);
                    
                    success = true;
                 catch (ex) 
                    console.log("saveBlob method failed with the following exception:");
                    console.log(ex);
                
                if (!success) 
                    var urlObject = window.URL || window.webkitURL || window;
                    var save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
                    save_link.href = urlObject.createObjectURL(blob);
                    save_link.download = filename;
                    var ev = document.createEvent("MouseEvents");
                    ev.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                    save_link.dispatchEvent(ev);
                
            , function (data, status) 
                console.log("Request failed with status: " + status);
            );
        

webapi代码

        public HttpResponseMessage TableToExcel(DataTable dt, string file)
        
            IWorkbook workbook;
            //string fileExt = Path.GetExtension(file).ToLower();
            string filetype = file.Substring(file.LastIndexOf("."));
            if (filetype == ".xlsx")  workbook = new XSSFWorkbook();  else if (filetype == ".xls")  workbook = new HSSFWorkbook();  else  workbook = null; 
            if (workbook == null)
            
                return new HttpResponseMessage(HttpStatusCode.NoContent);
            
            ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName);

            //表头  
            IRow row = sheet.CreateRow(0);
            for (int i = 0; i < dt.Columns.Count; i++)
            
                ICell cell = row.CreateCell(i);
                cell.SetCellValue(dt.Columns[i].ColumnName);
            

            //数据  
            for (int i = 0; i < dt.Rows.Count; i++)
            
                IRow row1 = sheet.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                
                    ICell cell = row1.CreateCell(j);
                    cell.SetCellValue(dt.Rows[i][j].ToString());
                
            
            //保存为Excel文件  

            try
            
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);

                var outputStream =new MemoryStream();
                workbook.Write(outputStream);
                outputStream.Flush();
                outputStream.Close();
                response.Content =  new ByteArrayContent(outputStream.GetBuffer());
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                response.Content.Headers.ContentDisposition.FileName = file;
                response.Content.Headers.ContentDisposition.FileNameStar = file;
                response.Content.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
                return response;
            
            catch (Exception ex)
            
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
                response.Content =new StringContent( ex.ToString());
                return response;
            
        

记录

1.中文文件名解析

后台添加配置说明:

ContentDisposition.FileNameStar会生成filename*=UTF-8‘‘XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX格式

 response.Content.Headers.ContentDisposition.FileNameStar = file;

前台接收:

 使用decodeURIComponent解码

 

var fileNameUnicode = res.headers("Content-Disposition").split("filename*=")[1];
                if (fileNameUnicode)  //当存在 filename* 时,取filename* 并进行解码(为了解决中文乱码问题)
                    filename = decodeURIComponent(fileNameUnicode.split("‘‘")[1]);
                

2.angular接收content-disposition内容

需要在服务器端进行配置。

  这个可以随意配置,只要你在response.Content.Headers中进行了配置,想让浏览器接收到信息

response.Content.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition,FileName,Extens,Others");

response.Content.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");

 

以上是关于Angular与.NET Webapi 文件下载的主要内容,如果未能解决你的问题,请参考以下文章

.NET Core 2 WebAPI CORS 与 Angular 4 前端和 Windows Auth 的问题

从 Angular 发布到 .net WebAPI

未发送从 Angular 到 .Net 5 webapi 的发布参数

.Net WebAPI Post 方法在 Angular2 服务中不起作用

Angular 7 .net 核心 2.2 WebApi Windows 身份验证 CORS

如何使用角度修改 asp.net 核心 WebAPI 的 asp.net 身份 UI