简体   繁体   中英

Download XML instead of open

I've got a page with a button that allows to download a XML file by address. At the beginning the js code connected to the button was:

function downloadURI(uri, name) {
  window.location = uri;
}

But all browsers opened the file instead of download it. Then I've tried with this code:

function downloadURI(uri, name) {
  var link = document.createElement("a");
  link.download = name;
  link.href = uri;
  link.click();
}

It works for IE, Edge, Opera and Chrome, but not on firefox. Can anyone help me solve it?

Firefox doesn't like clicks on links that aren't in the document. So append the link to document.body (or whatever) prior to the link.click call (and then remove it afterward, perhaps after a small setTimeout delay), eg:

function downloadURI(uri, name) {
  var link = document.createElement("a");
  link.download = name;
  link.href = uri;
  document.body.appendChild(link);
  link.click();
  setTimeout(function() {
    documet.body.removeChild(link);
  }, 50);
}

If that doesn't work in your setup, the way I've done this reliably is to make what the user clicks a link rather than a button, and have the link target a hidden iframe by name, and have the response to the link request contain the Content-Disposition: attachment; filename=foo Content-Disposition: attachment; filename=foo header, which tells the browser to download rather than open.

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