【问题标题】:Force downloading a file is not working in Safari browser强制下载文件在 Safari 浏览器中不起作用
【发布时间】:2016-12-09 14:24:28
【问题描述】:

我正在从跨域下载一个文件,它可以在 chrome 和 Firefox 中运行,但不能在 safari 中运行。 Chrome 和 Firefox 都在 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>

【问题讨论】:

    标签: javascript php jquery html .htaccess


    【解决方案1】:

    问题在于 Safari 浏览器在有效使用 Blob 时的浏览器兼容性。所以我只是删除了上面的 sn-p 并使用基本的锚标记进行操作。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-15
      • 2011-09-25
      • 1970-01-01
      • 1970-01-01
      • 2013-04-13
      • 2010-12-27
      • 2015-04-16
      • 1970-01-01
      相关资源
      最近更新 更多