JS实现点击按钮下载文件或提交表单

PS:本文说的,并非如何用js创建流、创建文件、实现下载功能。 而是说的:你已知一个下载文件的后端接口,前端如何请求该接口,实现点击按钮、下载文件到本地。(可以是zip啦、excel啦都是一样)


 

方法一:window.open("下载文件的后端接口");

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提交

 $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();
        });

方法三:通过a标签


var oA = document.createElement('a');
// 利用URL.createObjectURL()方法为a元素生成blob URL
oA.href = downUrl;
oA.target = '_black';
// 模拟点击
oA.click();
// 移除
oA.remove();

var downUrl = 'http://10.227.201.150/KDSImportExportService/FactSedoDtls/Export';
var odataUrl = this.AllDataSets["0"].EntityBaseUrl;
var userToken = " Bearer " + (window['Platform'].User && window['Platform'].User.UserToken) || "";
var temp = document.createElement("form");
temp.action = downUrl;
temp.method = "post";
temp.style.display = "none";
var hideInput = document.createElement("input");
hideInput.type="hidden";
//传入参数名,相当于get请求中的content=
hideInput.name= "odataUrl";
//传入数据,只传递了一个参数内容,实际可传递多个。
hideInput.value= odataUrl;
temp.appendChild(hideInput);
var hideInput2 = document.createElement("input");
hideInput2.type="hidden";
//传入参数名,相当于get请求中的content=
hideInput2.name= "token";
//传入数据,只传递了一个参数内容,实际可传递多个。
hideInput2.value= userToken;
temp.appendChild(hideInput2);
document.body.appendChild(temp);
temp.submit();

博文最后更新时间:


评论

  • entrepreneur en construction

    What?s up, I log on to your new stuff daily. Your writing style is awesome, keep it up! https://constructionlabrie.com

  • 0.6 C Decking

    Heya i'm for the first time here. I came across this board and I find It truly useful & it helped me out much. I hope to give something back and help others like you aided me. http://birudo.s5.xrea.com/cgi-bin/msgy1/msgbrd.cgi

  • hair bundles

    Some splendid images. Amazing shades. http://hairremovalcare.simpsite.nl/

  • GO Tape videos

    If some one needs expert view regarding blogging afterward i suggest him/her to visit this webpage, Keep up the good job. https://theratape.com/lp_3259-go-tape-videos

  • entrepreneur en construction

    Hi there, I log on to your blogs regularly. Your writing style is awesome, keep it up! https://constructionlabrie.com

  • hairstyles for short hair

    Very nice depth -) https://justpaste.it/80p0p

发表评论

博客统计

访问量:5097065

博文总数:750 评论总数:909179

原创126 翻译20 转载604