简体   繁体   中英

Force downloading a file is not working in Safari browser

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM