Download files with JS (requires backend link)

Source: Internet
Author: User
Tags button type

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.