使用 AngularJS 下载文件 [英] Download a file with AngularJS
问题描述
我需要提供一个下载文件的链接,该链接必须隐藏并且任何用户都可以访问,这是我的代码,没有任何错误,但我什至无法打开下载对话框:
I need to provide a link to download a file, the link must be hidden and accessible by any users, Here is my code , there are no errors whatsoever, but I can't even get the download dialog box to open:
模板
<a ng-href="#" target="page" type="button" class="btn"
ng-click="download()">Download</a>
脚本文件
$scope.download = function(){
//here i need to know the code,can anybody explain me
}
推荐答案
首先,您不能在基于 Web 的技术 (HTML/CSS/JavaScript) 应用程序中隐藏/不公开"链接.下载由客户端处理,因此下载/链接 URL 必须是公开的.您可以尝试隐藏"保护参数,例如使用后端执行的编程语言(如PHP 或 node.js 等")下载 URL 中的 ID.通过这种方式,您可以创建 hash
网址,例如 http://www.myside.com/download/359FTBW!S3T387IHS
以隐藏诸如 recordId
之类的参数> 在您的网址中.
First of all, your can't "hide/not public" a link in a web based technology (HTML/CSS/JavaScript) application. Downloads are handled by the client, so the Download/Link-URL must be public. You can try to "hide" protective params like e.g. IDs in the download URL by using a backend executed programming language like "PHP or node.js, etc.". In that way you can create hash
URLs like http://www.myside.com/download/359FTBW!S3T387IHS
to hide parameters like the recordId
in your URL.
知道了这一点,您的解决方案就很简单了.只需使用 HTML 属性下载 就像 <a href="http://mydownloadurl"下载>链接文本
强制浏览器下载href
源.这里不需要 ng-click
.不幸的是,Safari 浏览器不支持 download
属性.当浏览器自己处理下载时,这并不重要.根据用户系统操作系统配置,文件将被下载或直接在安装在该系统上的程序中打开.例如,如果某些 pdf 查看器应用程序可用,则会在 PDF 查看器中打开 PDF 文件.
By knowing this, your solution is pretty easy. Just use the HTML attribute download like <a href="http://mydownloadurl" download>link text</a>
to force the browser to download the href
source. No ng-click
is needed here. Unfortunately the download
attribute is not supported by Safari browser. This doesn't realy matter while the browser is handling the download itself. Depending on the users system OS configuration the file will be downloaded or directly opened in a programm installed on that system. For example, a PDF file will be opened in a PDF Viewer if some pdf viewer application is available.
我写了一个 Plunker 处理 ng-href
在 AngularJS 控制器 $scope
中.我希望这是你需要的.
I wrote a Plunker which handles ng-href
in a AngularJS controller $scope
. I hope this is what you need.
您的控制器:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.fileHref = 'http://www.analysis.im/uploads/seminar/pdf-sample.pdf';
});
您的观点:
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.14/angular.js" data-semver="1.3.14"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<a ng-href="fileHref" download="yourFilename">Download</a>
</body>
</html>
这篇关于使用 AngularJS 下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!