【问题标题】:How to know my file download Url is invalid using angularjs如何使用 angularjs 知道我的文件下载 URL 无效
【发布时间】:2021-04-19 22:54:23
【问题描述】:

我的 AngularJS 组件中有一个链接到文件的锚标记,但我希望能够检测该位置的文件是否存在以发出警报消息。如何做到这一点?

<a ng-href="{{row.General_FileJson.DiskPath}}" download="{{row.General_FileJson.Name}}">file download</a>

【问题讨论】:

  • 假设您没有被 CORS 阻止,您可以发送 AJAX HEAD 请求并检查响应。
  • 当我尝试下载无效的源文件时,它会尝试下载文件并说下载失败。

标签: javascript angularjs file downloadfile


【解决方案1】:

    $scope.getFile = function (path, file) {
        $http.get(path).success(function (result) {
            console.log(result);
            var a = document.createElement("a");
            document.body.appendChild(a);
            a.style = "display: none";
            a.href = path;
            a.download = file;
            a.click();
            window.URL.revokeObjectURL(url);
        }).error(function (result, status) {
            $scope.HasError = true;
            $scope.ErrorMsg = "Unable to download this file! ";
            alertError($scope.ErrorMsg);

        });
    }
<a href="" ng-click="getFile(Url, FileName)">file download</a>

【讨论】:

    【解决方案2】:

    您可以使用 JavaScript(或者更确切地说是 TypeScript)对 url 进行异步调用并检查状态代码:

    var request = new XMLHttpRequest();  
    request.open('HEAD', 'http://www.mozilla.org', true);
    request.onreadystatechange = function(){
        if (request.readyState === 4){
            if (request.status === 404) {  
                alert("This file does not exist!");
            }  
        }
    };
    request.send();
    

    上面的例子只是普通的 JavaScript,当然你也可以使用一个库,甚至是一个专用的 Angular 服务。

    【讨论】:

    • 是的,这很有帮助。谢谢
    猜你喜欢
    • 2022-11-05
    • 1970-01-01
    • 2018-10-24
    • 2023-03-20
    • 2017-07-10
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多