Detect when browser receives file download

前端 未结 22 1684
陌清茗
陌清茗 2020-11-21 04:55

I have a page that allows the user to download a dynamically-generated file. It takes a long time to generate, so I\'d like to show a \"waiting\" indicator. The problem is,

22条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-21 05:48

    Greetings, I know that the topic is old but I leave a solution that I saw elsewhere and it worked:

    /**
     *  download file, show modal
     *
     * @param uri link
     * @param name file name
     */
    function downloadURI(uri, name) {
    // <------------------------------------------       Do someting (show loading)
        fetch(uri)
            .then(resp => resp.blob())
            .then(blob => {
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = url;
                // the filename you want
                a.download = name;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                // <----------------------------------------  Detect here (hide loading)
                alert('File detected'));
            })
            .catch(() => alert('An error sorry'));
    }
    

    You can use it:

    downloadURI("www.linkToFile.com", "file.name");
    
    

提交回复
热议问题