js 文件下載 進度條
阿新 • • 發佈:2017-10-27
href com ron 事件 回調 function set sta let
js:
/** * 下載文件 - 帶進度監控 * @param url: 文件請求路徑 * @param name: 保存的文件名 * @param progress: 進度處理回調函數
* eg: progressDownLoad({url:‘http://loacalhost:8080/downLoad.action‘,‘file.rar‘,progress:function(percent){
* console.log(percent);
* }}); **/ function progressDownLoad({url,filename,progress}){var req = new XMLHttpRequest(); req.open("POST", url, true); //監聽進度事件 req.addEventListener("progress", function (evt) { if (evt.lengthComputable) { var percentComplete = evt.loaded / evt.total; if(progress) try{ progress.call(percentComplete); }catch(e){} } }, false); req.responseType = "blob"; req.onreadystatechange = function () { if (req.readyState === 4 && req.status === 200) { if (typeof window.chrome !== ‘undefined‘) { // Chrome version var link = document.createElement(‘a‘); link.href= window.URL.createObjectURL(req.response); link.download = filename; link.click(); } else if (typeof window.navigator.msSaveBlob !== ‘undefined‘) { // IE version var blob = new Blob([req.response], { type: ‘application/force-download‘ }); window.navigator.msSaveBlob(blob, filename); } else { // Firefox version var file = new File([req.response], filename, { type: ‘application/force-download‘ }); window.open(URL.createObjectURL(file)); } } }; req.send(); }
js 文件下載 進度條