paulwong

AJAX下载+监控进度+保存文件

全程用AJAX下载文件,并显示下载进度,之后保存文件。

HTML5文件:

<!DOCTYPE html>
<html>
<head>
    <title>XMLHttpRequest Download Progress</title>
</head>
<body>
    <progress id="p"></progress>
    <input type="button" onclick="downloadAndSave();" value="Download"/>
    <script>
        
function downloadAndSave()
        {
            
var progressBar = document.getElementById('p'), xhr = new XMLHttpRequest();
            xhr.open('GET', '
2');
            xhr.responseType 
= "arraybuffer";
            xhr.onprogress 
= function(event) {
                
if(event.lengthComputable) {
                    progressBar.max 
= event.total;
                    progressBar.value 
= event.loaded;
                }
            };
            xhr.onloadend 
= function(event) {
                progressBar.value 
= event.loaded;
                saveByeToFile('
2', xhr.response);
            };
            xhr.send();
        }
        
        
function saveByeToFile(name, arrayBuffer) {
            
var byteArray = new Uint8Array(arrayBuffer);
            
var a = window.document.createElement('a');

            a.href 
= window.URL.createObjectURL(new Blob([ byteArray ], {
                type : 'application
/octet-stream'
            }));
            a.download 
= name;

            
// Append anchor to body.
            document.body.appendChild(a)
            a.click();

            
// Remove anchor from body
            document.body.removeChild(a)
        }
    
</script>
</body>
<html>

posted on 2015-08-06 19:17 paulwong 阅读(752) 评论(0)  编辑  收藏 所属分类: HTML5


只有注册用户登录后才能发表评论。


网站导航: