在单击href链接的同时下载文件

Download a file while clicking on href link?

本文关键字:下载 文件 单击 href 链接      更新时间:2023-09-26

当我使用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();
        }
    })
}

EDIT:如果您正在寻找本地HTML解决方案,您也可以使用下载属性

<a href="path" download>Download File</a>

download属性也支持filename。

我以前需要使用AngularJS来做到这一点,我使用了angular文件保护程序库。

下面的代码使用您最初的RESTCaller.getConfig(...)函数,但随后使用$http提供程序来获取文件内容,从返回的缓冲区中创建Blob对象,然后最后调用angular-file-saversaveAs函数来执行浏览器下载。

$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相关的示例。