[英]Download a file while clicking on href link?
当我使用ng-click
文件时,有什么方法可以下载文件吗? 这就是我现在拥有的:
<a ng-href="../api/rest/admin/v1/syncsessions/export?fileKey={{syncObject.sourceFiles}}">Download file</a>
这似乎工作正常。 但是,问题是,当我点击href
,我会被重定向到一个带有url的页面。 结果,我想做这样的事情:
<a ng-click="getExportFiles({{syncObject.sourceFiles}})">Download File</a>
其中getExportFiles定义如下:
var baseSyncUrl = "../api/rest/admin/{{path.version}}/syncsessions";
var exportSyncFileReq = {method: "GET", url: baseSyncUrl + "/export", params: {fileKey: ""}, path: {version: "v1"}};
$scope.getExportFiles = function(fileKey) {
var req = exportSyncFileReq;
req.params.fileKey = fileKey;
var data = RESTCaller.getConfig(req);
data.then(function(result) {
if(result) {
return result;
}
})
}
结果中包含的是文件的链接,例如,它将是https://<insertURL>
因为RESTCaller
在调用了定义的exportSynceFileReq
API后展开了我的promise
。 问题是,当我ng-click
,没有任何反应。 该文件未下载。 如果我做
<a ng-href="{{getExportFiles(syncObject.sourceFiles)}}">Download File</a>
我得到一个无限的消化循环。 有没有办法我只需点击一个链接,调用我的API,然后自动下载文件而不重定向到另一个页面? 任何帮助,将不胜感激。 谢谢!
如果您有来自服务器的链接,您可以尝试使用虚拟链接并单击它:
$scope.getExportFiles = function(fileKey) {
var req = exportSyncFileReq;
req.params.fileKey = fileKey;
var data = RESTCaller.getConfig(req);
data.then(function(result) {
if (result) {
var link = document.createElement('a');
//link.download = 'filename.ext';
link.href = result;
link.click();
}
})
}
我之前需要使用AngularJS完成此操作,并且我使用了angular-file-saver库。
下面的代码使用你的初始RESTCaller.getConfig(...)
函数,但是然后使用$http
提供程序获取文件内容,从返回的缓冲区中创建一个Blob对象,最后调用angular-file-saver
's saveAs
功能执行浏览器下载。
$scope.getExportFiles = function(fileKey) {
// Build the URL we're wanting to fetch
RESTCaller.getConfig({
method: "GET",
url: baseSyncUrl + "/export",
params: {
fileKey: fileKey.toString()
},
path: { version: "v1" }
}).then(function(result) {
// Assuming result is the URL of the download file.
var fetchUrl = result.toString();
// Check if the current browser has support for Blob objects
try { var blobSupport = !!new Blob; } catch (e) {}
// If there is Blob support, use the angular-file-saver library
// to download the file
if (blobSupport) {
$http
.get(fetchUrl, {}, { responseType: 'arraybuffer' })
.then(function(response) {
saveAs(new Blob([ response.data ], {
// You need to specify the file format for the browser
// to handle the download correctly. Whether this is hard-coded
// or dynamically returned by your API is up to you.
type: 'application/octet-stream'
}), fileKey);
});
} else {
// Use some other method a retrieving the file, whether
// that be creating an 'A' element in the DOM and triggering
// the 'click' event, or using $window
$window.open(fetchUrl);
}
});
};
您可以在此处找到有关Blob对象的更多信息。
你可以在这个jsFiddle中看到一些其他与Blob相关的例子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.