且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是二进制文件(pdf,word,excel,ppt,mp3,...)可以使用XHR或fetch下载?

更新时间:2023-10-17 12:37:04

传输编码对浏览器中的应用程序应该是透明的,不要担心。

以下是一个基本的ajax文件下载解决方案,它使用XHR2,blob和具有下载属性的锚点。

The transfer encoding should be transparent to an application in a browser, don't worry about it.
Below is a basic ajax file download solution, it uses XHR2, blobs and anchors with download properties.

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    if (this.readyState == 4 && this.status == 200){
        var blobURL = window.URL.createObjectURL(this.response); 
        var anchor = document.createElement('a');
        anchor.download = 'filename.ext';
        anchor.href = blobUrl;
        anchor.click();
    }
}
xhr.open('GET', request_url);
xhr.setRequestHeader('Authorization', 'Bearer ' + GOOGLE_ACCESS_TOKEN);
xhr.responseType = 'blob'; // Get a binary response
xhr.send(jData);