首页 > Web开发 > 详细

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

时间:2015-08-07 02:01:47      阅读:215      评论:0      收藏:0      [点我收藏+]

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>

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

原文:http://www.blogjava.net/paulwong/archive/2015/08/06/426641.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!