download files with JS
PS: In this article, not how to create a stream with JS, create files, implement the download function.
Instead, you know a back-end interface that downloads files, how the front-end requests the interface, implements the Click button, and downloads the file locally. (Can be zip, Excel is the same)
There are two methods: window.open () and submit via form table forms.
Online Example: https://hamupp.github.io/gitblog/app/jsBasic/jsButtonDownloadFile/index.html
Method One: window.open ("Back-end interface for downloading files");
*html structure *
<button type= "button" id= "btn1" > Download a Zip (Method 1) </button><button type= "button" id= "BTN2" > Download a Zip (Method 2) </button>
/*js Part */
var $eleBtn 1 = $ ("#btn1"); var $eleBtn 2 = $ ("#btn2"); A back-end interface that is known to download a file: Https://codeload.github.com/douban/douban-client/legacy.zip/master //Method One: window.open () $eleBtn 1.click (function () { window.open ("https://codeload.github.com/douban/douban-client/legacy.zip/ (master "); });
However, there is a problem: the browser will open a new window, and then quickly and automatically close, the experience is very bad.
Method Two: Submit through form
Because the return type of the AJAX function is only XML, text, JSON, HTML and other types, there is no "stream" type, so through Ajax to request that the interface is unable to download the file, so we create a new form element to request the interface.
/*js Part */
Method two: Through form $eleBtn 2.click (function () { var $eleForm = $ ("<form method= ' get ' ></form>"); $eleForm. attr ("Action", "Https://codeload.github.com/douban/douban-client/legacy.zip/master"); $ (document.body). Append ($eleForm); Submit the form for download $eleForm. Submit (); });
Download files with JS (requires backend link)