How to download files from the front end

One: The backend gives the url, if you use a link to open this url is the preview
<span onclick="getFileAndDownload('图片名称','图片路径')">下载png测试</span>
<br />
<span onclick="getFileAndDownload('pdf名称','pdf路径')">下载pdf测试</span>
<br />
<script src="./js/jquery-1.12.4.js"></script>
function getFileAndDownload(fileName, url) {
        var x = new XMLHttpRequest();
        x.open("GET", url, true);
        x.responseType = 'blob';
        x.onload = function (e) {
            var blob = x.response;
            if ('msSaveOrOpenBlob' in navigator) {//IE导出
                window.navigator.msSaveOrOpenBlob(blob, fileName);
            }
            else {
                var a = document.createElement('a');
                a.download = fileName;
                a.href = URL.createObjectURL(blob);
                $("body").append(a);
                a.click();
                $(a).remove();
            }
        };
        x.send();
    }

Guess you like

Origin blog.csdn.net/weixin_43996999/article/details/104532781