[英]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.