问题
I understand that opening a new window with a URL essentially issues a GET request for that specified URL. I have a URL that when opening using window.open(), a a browser download is triggered. However, when I issue an actual GET request via AJAX, why does the response not trigger a browser download?
回答1:
You can only trigger browser download by redirecting the browser tab to the download URL, it is not possible to do it using AJAX request.
When the browser (as in: the current URL loaded in the browser's tab) visits a URL, it is the browser's responsibility to handle the response. For file downloads, the appropriate action to handle the response is to show a download dialog. When you perform a GET request through AJAX though, it is your responsibility to handle the response, not the browser's. The response may contain any data and most of the time the browser wouldn't even understand what that data means.
If what you're trying to achieve is a delayed download start (like SourceForge and others do) or to show you a post-download page then start a download, that can be achieved by redirecting to the post-download page, and starting a Javascript timer there that then redirects the browser (not just AJAX, but the window.location
) to the download URL. The way browsers usually handle this, the post-download page will remain loaded and you'll get a download dialog.
来源:https://stackoverflow.com/questions/33786773/using-window-openurl-self-opens-download-window-but-not-get-request