当前位置: 首页 > 编程语言 > C#

尝试使用angularJS和c#webapi从服务器下载文件分享

时间:2023-04-10 12:31:07 C#

C#学习教程:尝试使用angularJS和c#webapi从服务器下载文件没有损坏的文件。但是,当我下载文件时(纯txt:s除外,它们是woork),它们会变大并损坏。经过大量调查,我不知道可能是什么问题。我只是将文件作为流写入响应并下载blob。欢迎任何想法!使用AngularJS从ASP.NETWebAPI方法下载文件现在行守则如下;的WebAPI:[Route("GetFile")]publicHttpResponseMessageGetFile(){HttpResponseMessageresult=null;//在这里获取文件对象try{IEnumerableheaderValues=Request.Headers.GetValues("fileID");intkey=Int32.Parse(headerValues.FirstOrDefault());varfetchFile=db.FileRecords.Single(a=>a.id==key);varlocalFilePath=fetchFile.path+fetchFile.name;如果(!System.IO.File.Exists(localFilePath)){结果=Request.CreateResponse(HttpStatusCode.Gone);}else{//将文件提供给客户端//我使用了x-filename标头来发送文件名。这是为方便起见的自定义标头。//您也应该为响应设置内容类型mime标头,以便浏览器知道数据格式。varinfo=System.IO.File.GetAttributes(localFilePath);结果=Request.CreateResponse(HttpStatusCode.OK);result.Content=newStreamContent(newFileStream(localFilePath,FileMode.Open,FileAccess.Read));result.Content.Headers.ContentType=newMediaTypeHeaderValue("application/octet-stream");result.Content.Headers.Add("x-filename",fetchFile.name);result.Content.Headers.ContentDisposition=newSystem.Net.Http.Headers.ContentDispositionHeaderValue("附件");result.Content.Headers.ContentDisposition.FileName=fetchFile.name;}返回结果;}catch(Exceptione){returnRequest.CreateResponse(HttpStatusCode.BadRequest);}}图像:下载文件控制器:/********FILEDOWNLOAD**********/$scope.downloadFiles=function(file){$http({method:'GET',缓存:false,url:host+'api/Files/GetFile',headers:{'Content-Type':'application/json;charset=utf-8','fileID':file.id}}).success(function(data,status,headers){varoctetStreamMime='application/octet-stream';varsuccess=false;//获取标头headers=headers();//从x-filename标头或默认获取文件名到“下载.bin”varfilename=headers['x-filename']||'下载.bin';//从头部判断内容类型或默认为“application/octet-stream”varcontentType=headers['content-type']||八位字节流Mime;尝试{console.log(文件名);//如果支持,请尝试使用msSaveBlobconsole.log("TryingsaveBlobmethod...");varblob=newBlob([data],{type:contentType});if(navigator.msSaveBlob)navigator.msSaveBlob(blob,文件名);else{//如果可用,尝试使用其他saveBlob实现varsaveBlob=navigator.webkitSaveBlob||导航器.mozSaveBlob||导航器.saveBlob;if(saveBlob===undefined)抛出“不支持”;saveBlob(blob,文件名);}console.log("saveBlob成功");成功=真;}catch(ex){console.log("saveBlob方法失败,出现以下异常:");控制台日志(前);}if(!success){//获取bloburl创建者varurlCreator=window.URL||窗口.webkitURL||窗口.mozURL||窗口.msURL;如果(urlCreator){//尝试使用下载链接varlink=document.createElement('a');if('download'inlink){//尝试模拟点击try{//准备一个blobURLconsole.log("Tryingdownloadlinkmethodwithsimulatedclick...");varblob=newBlob([data],{type:contentType});varurl=urlCreator.createObjectURL(blob);link.setAttribute('href',url);//设置下载属性(Chrome14+/Firefox20+支持)link.setAttribute("download",filename);//模拟点击下载链接varevent=document.createEvent('MouseEvents');event.initMouseEvent('点击',true,true,window,1,0,0,0,0,false,false,false,false,0,null);link.dispatchEvent(事件);console.log("模拟点击下载链接方法成功");成功=真;}catch(ex){console.log("使用模拟点击下载链接方法失败,出现以下异常:");控制台日志(前);}}if(!success){//回退到window.location方法try{//PrepareablobURL//在使用window.location强制下载时使用application/octet-streamconsole.log("Tryingdownloadlinkmethodwithwindow.location...");varblob=newBlob([data],{type:octetStreamMime});varurl=urlCreator.createObjectURL(blob);window.location=url;console.log("使用window.location下载链接方法成功");成功=真;}catch(ex){console.log("使用window.location下载链接方法失败,出现以下异常:");控制台日志(前);}}}}if(!success){//回退到window.open方法console.log("Nomethodsworkedforsavingthearraybuffer,usinglastresortwindow.open");window.open(httpPath,'_blank','');}/******************/}).error(function(data,status){console.log("请求失败,状态:"+status);//可选择将错误写入范围//$scope.errorDetails="Requestfailedwithstatus:"+status;});}添加了arraybuffer作为GET请求的响应类型,现在浏览器正确解释文件以上就是C#学习教程:尝试使用angularJS和c#webapi从服务器下载文件分享的全部内容。如果对大家有用,需要进一步了解C#学习教程,希望大家多加关注——/********FILEDOWNLOAD************/$scope.downloadFiles=function(file){$http({method:'GET',cache:false,url:host+'api/Files/GetFile',responseType:'arraybuffer',headers:{'Content-Type':'application/json;charset=utf-8','fileID':file.id}本文收集自网络,不代表立场,如涉及侵权,请点击右侧联系管理员删除.若转载请注明出处: