2016-12-08 177 views
0

我正在从跨域下载文件,并且它在Chrome和Firefox中都可用,但在Safari浏览器中无法正常工作。当Safari播放歌曲时,Chrome和Firefox都在下载。这是Safari的bug,但有人解决,我不太明白。请帮助我。强制下载文件在Safari浏览器中不起作用

注意:给一个小错误:Failed to load resource: Frame load interrupted

客户方代码:

var url = "http://www.example.com/song.mp3"; 
var xhr = createCORSRequest('GET', url); 
    if (!xhr) { 
    alert('CORS not supported'); 
    return; 
    }  
    xhr.responseType = 'blob';  
    xhr.onload = function() { 
    var a = document.createElement('a'); 
    a.href = window.URL.createObjectURL(xhr.response); 
    a.download = 'FileName.mp3'; 
    a.style.display = 'none'; 
    document.body.appendChild(a); 
    a.click(); 
    delete a; 
    };  
    xhr.onerror = function() { 
    alert('Woops, there was an error making the request.'); 
    }; 
     xhr.send(); 
} 

function createCORSRequest(method, url) { 
    var xhr = new XMLHttpRequest(); 
    if ("withCredentials" in xhr) { 
    // XHR for Chrome/Firefox/Opera/Safari. 
    xhr.open(method, url, true); 
    } else if (typeof XDomainRequest != "undefined") { 
    // XDomainRequest for IE. 
    xhr = new XDomainRequest(); 
    xhr.open(method, url); 
    } else { 
    // CORS not supported. 
    xhr = null; 
    } 
    return xhr; 
} 

服务器端代码:

.htaccess文件

<FilesMatch "\.('mp3')$"> 
    ForceType application/octet-stream 
    Header set Content-Disposition attachment 
</FilesMatch> 

回答

0

的问题是Safari浏览器的浏览器的兼容性浏览器有效使用Blob。所以我刚刚删除了上面的代码片段,并为我的操作使用了基本的锚标签。

if(navigator.userAgent.indexOf("Safari") != -1){  
     var a = $("<a>").attr("href", url).attr("download", "MyFile.mp3").appendTo("body"); 
     a[0].click(); 
     a.remove();  
} 
相关问题