js,接管浏览器下载操作

使用js,接管浏览器下载操作

var xhr = new XMLHttpRequest();
                    //http://192.168.25.133/group1/M00/00/00/wKgZhV63vh2ADogjChXGNk0PUxQ200.war
                    xhr.open('GET', 'aaa.docx',true);//也可使用文件url,但可能存在跨域问题
                    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                    xhr.responseType = "blob";
                    xhr.onprogress = function (event) {
                        if (event.lengthComputable) {
                        	//此处是计算下载进度,不是本文重点,就不上代码了
                            add(GetPercent(event.loaded,event.total));
                            document.getElementById("jdk").style.display = "block";
                            console.log(event.loaded);
                            console.log(event.total);
                        }
                    };
                    xhr.onload = function (oEvent) {
                        console.log(oEvent);
                        console.log(xhr.status);
                        console.log(xhr.response);
                        if (xhr.readyState === 4 && xhr.status === 200) {
                            // var name = xhr.getResponseHeader("Content-disposition");
                            // var filename = name.substring(20,name.length);
                            var blob = new Blob([xhr.response]);
                            var csvUrl = URL.createObjectURL(blob);
                            var link = document.createElement('a');
                            link.href = csvUrl;
                            link.download = 'aaa.docx';
                            link.click();
                        }
                    }
                    xhr.send();

你可能感兴趣的:(js,接管浏览器下载操作)