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>