dongli8466 2016-12-08 12:00
浏览 333

强制下载文件在Safari浏览器中不起作用

I'm downloading a file from cross-domain and its working both in chrome and Firefox but not working in safari. Both Chrome and Firefox are downloading where as Safari is playing the song. It's safari bug but solved by somebody and I didn't quite get it. Please do help me.

Note: Giving a small error : Failed to load resource: Frame load interrupted

Clientside code:

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;
}

ServerSide Code:

.htaccess file

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

1条回答 默认 最新

  • dongmibeng5885 2016-12-09 06:15
    关注

    The problem is browser compatibility of Safari browser in effective usage of the Blobs. So I just removed the above snippet and used the basic anchor tag for my operations.

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

报告相同问题?

悬赏问题

  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?