简体   繁体   中英

Javascript: How to download zip from API server via Firefox browser?

Currently, I have implemented the following and it works on the Chrome browser. But on the Firefox browser, it gets the response from the API server, but nothing is being downloaded to the Firefox browser.

What could I be doing wrong? Is the following not cross-platform compatible?

Thank you in advance

Here is the code:

var config = {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify(...)
}

fetch("https://test-server.com:8080/download/zip", config)
      .then(response => response.blob())
      .then(zipFile => {
        console.log(zipFile)

        var blob = zipFile;
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = 'download'
        link.click();
      })
      .catch((error) => {
        console.log("Error: ", error)
      })

On Chrome, console.log(zipFile) would log something like: Blob {size: 504188, type: "application/zip"} but on Firefox, it logs Blob {size: 504188, type: "" } .

Could it be because the link element isn't attached to the body?

When I tried the following it worked in Chrome but not Firefox (like you're experiencing):

link = document.createElement('a')
link.href = 'http://google.com'
link.click()

but

link = document.createElement('a')
link.href = 'http://google.com'
document.body.appendChild(link)
link.click()

worked in Firefox as well.

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