JS實現點擊按鈕,下載檔案

來源:互聯網
上載者:User

標籤:document   ajax   button   htm   tps   win   開啟   target   type   

PS:本文說的,並非如何用js建立流、建立檔案、實現下載功能。

而是說的:你已知一個下載檔案的後端介面,前端如何請求該介面,實現點擊按鈕、下載檔案到本地。(可以是zip啦、excel啦都是一樣)

 

有兩個方法:window.open()和通過form表單來提交。

線上例子:https://hamupp.github.io/gitblog/app/jsBasic/jsButtonDownloadFile/index.html

方法一:window.open("下載檔案的後端介面");

*html結構*

<button type="button" id="btn1">下載一個zip(方法1)</button><button type="button" id="btn2">下載一個zip(方法2)</button>

/*js部分*/

var $eleBtn1 = $("#btn1");        var $eleBtn2 = $("#btn2");        //已知一個下載檔案的後端介面:https://codeload.github.com/douban/douban-client/legacy.zip/master        //方法一:window.open()        $eleBtn1.click(function(){            window.open("https://codeload.github.com/douban/douban-client/legacy.zip/master");        });

然而有個問題:瀏覽器會開啟一個新視窗,然後迅速自動關閉,體驗非常不好。

方法二:通過form提交

由於ajax函數的傳回型別只有xml、text、json、html等類型,沒有“流”類型,所以通過ajax去請求該介面是無法下載檔案的,所以我們建立一個新的form元素來請求介面。

/*js部分*/

//方法二:通過form        $eleBtn2.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);            //提交表單,實現下載            $eleForm.submit();        });

 

JS實現點擊按鈕,下載檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.