在我们的Angular JS应用程序中,我只是通过调用window.location
来下载文件。
HTML:
<div class="row">
<div class="col-md-3 col-sm-4 col-xs-6" ng-repeat="file in files">
<div class="well well-sm truncate">
<a href="" title="Download {{file.FileName}}" ng-click="download(file)" ><b>{{file.FileName}}</b></a><br />
<small>{{(file.FileSize/1024)|number:2}} KB</small><br />
<i class="fa fa-trash CP text-danger pull-right" ng-show="mUser.Role>=20" title="Delete file" ng-click="deletefiles(file.AttID)"></i>
<small>Uploaded by <a href="user/{{file.AddedBy}}">{{file.AddedByName}}</a> on {{file.Created|date:'dd MMM yyyy'}}</small>
</div>
</div>
</div>
角度方法:
$scope.download = function (ff) {
if (confirm('Download this file?')) window.location = "api/files/download?token=" + $rootScope.token + "&IDKey=" + ff.IDKey;
}
Web API控制器方法:
[HttpGet]
public HttpResponseMessage download(string Token, string IDKey)
{
HttpResponseMessage lResponse = new HttpResponseMessage(HttpStatusCode.OK);
// Validate request
Result lRes = UserClass.GetUserByToken(Token);
if (!lRes.IsSuccess)
{
lResponse.Content = new StringContent("User Token is invalid");
lResponse.StatusCode = HttpStatusCode.Forbidden;
return lResponse;
}
// Get File object
AttClass lAtt = AttClass.GetFile(IDKey);
if (!lAtt.IsOk)
{
lResponse.Content = new StringContent("Attachment ID Key is invalid");
lResponse.StatusCode = HttpStatusCode.NotFound;
return lResponse;
}
// Return file
lResponse.Content = new StreamContent(new FileStream(lAtt.GetFullPath(), FileMode.Open, FileAccess.Read));
lResponse.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = lAtt.FileName };
lResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return lResponse;
}
当Token
和IDKey
有效时,文件下载效果非常好。但是,在其他情况下,会向用户显示一个带有简单错误消息的空白页面。我可以阻止这种情况,只是在原始页面上显示警报,并说明下载失败的原因吗?
PS:我不想要使用HTML5 SaveAs功能或filesaver.js。
答案 0 :(得分:1)
你可以试试这个
1-您是否尝试使用iframe而不是使用下载文件 window.location的
document.getElementById("myiframe").src="api/files/download?token=" + $rootScope.token + "&IDKey=" + ff.IDKey;
并检查iframe正文
document.getElementById('myiframe').contentDocument.body.innerHTML
重新编辑
document.getElementById("myiframe").src="your url";
document.getElementById("myiframe").addEventListener("load",
function(){
console.log(this.contentDocument.contentType);
if(!(document.getElementById("myiframe").contentDocument.contentType=="application/octet-stream"))
alert("Downlaod Failed");
else
alert("Thank you for downloading");
});
答案 1 :(得分:0)
使用window.location
时处理服务器响应非常困难。
您可以在angularJs中使用ajax调用进行下载,也可以检查您的响应。
$http({
url: 'server/url',
method: "POST",
responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
//check your response here
//smaple code for excel download
var blob = new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
var objectUrl = URL.createObjectURL(blob);
var anchor = angular.element('<a/>');
anchor.attr({
href: objectUrl,
target: '_blank',
download: fileName + '_' + new Date().getTime() + '.xlsx'
})[0].click();
}).error(function (data, status, headers, config) {
});
`