正文
有時(shí)候我們?cè)诰W(wǎng)頁上需要增加一個(gè)下載按鈕,讓用戶能夠點(diǎn)擊后下載頁面上的資料,那么怎樣才能實(shí)現(xiàn)功能呢?這里有兩種方法:
現(xiàn)在需要在頁面上添加一個(gè)下載按鈕,點(diǎn)擊按鈕下載文件。
題外話,這個(gè)下載圖標(biāo)是引用的 font-awesome 上面的。使用時(shí),首先將 font-awesome 整個(gè)文件夾下載下來,利用bower或者是自己去官網(wǎng)上面下載都行。
將整個(gè)文件夾放在項(xiàng)目文件中之后,在頁面上面引入css文件
<link href="libs/font-awesome-4.7.0/css/font-awesome.min.css" type="text/css" rel="stylesheet">
在頁面上可以開始使用所需要的圖標(biāo)了
<i class="fa fa-download" aria-hidden="true" title="下載"></i>
1.下載項(xiàng)目中的文件
如果要下載的是一個(gè)excel文件模板,可以先將該文件放在項(xiàng)目文件夾下面,然后在頁面下載按鈕上加上onclick事件:
<i class="fa fa-download" aria-hidden="true" title="下載" onclick="window.open('file/user.xlsx')"></i>
這樣在點(diǎn)擊圖標(biāo)之后,文件就會(huì)自動(dòng)下載了。
2.發(fā)送請(qǐng)求地址下載文件
JQuery的ajax函數(shù)的返回類型只有xml、text、json、html等類型,沒有“流”類型,所以我們要實(shí)現(xiàn)ajax下載,不能夠使用相應(yīng)的ajax函數(shù)進(jìn)行文件下載。但可以用js生成一個(gè)form,用這個(gè)form提交參數(shù),并返回“流”類型的數(shù)據(jù)。在實(shí)現(xiàn)過程中,頁面也沒有進(jìn)行刷新。
1)get請(qǐng)求
$('.download').click(function () {var tt = new Date().getTime();var url = 'http://192.168.1.231:8080/91survey/ws/excel/download';/*** 使用form表單來發(fā)送請(qǐng)求* 1.method屬性用來設(shè)置請(qǐng)求的類型――post還是get* 2.action屬性用來設(shè)置請(qǐng)求路徑。* */var form=$("<form>");//定義一個(gè)form表單form.attr("style","display:none");form.attr("target","");form.attr("method","get"); //請(qǐng)求類型form.attr("action",url); //請(qǐng)求地址$("body").append(form);//將表單放置在web中 /*** input標(biāo)簽主要用來傳遞請(qǐng)求所需的參數(shù):** 1.name屬性是傳遞請(qǐng)求所需的參數(shù)名.* 2.value屬性是傳遞請(qǐng)求所需的參數(shù)值.** 3.當(dāng)為get類型時(shí),請(qǐng)求所需的參數(shù)用input標(biāo)簽來傳遞,直接寫在URL后面是無效的。* 4.當(dāng)為post類型時(shí),queryString參數(shù)直接寫在URL后面,formData參數(shù)則用input標(biāo)簽傳遞* 有多少數(shù)據(jù)則使用多少input標(biāo)簽* */var input1=$("<input>");input1.attr("type","hidden");input1.attr("name","tt");input1.attr("value",tt);form.append(input1);var input2=$("<input>");input2.attr("type","hidden");input2.attr("name","companyId");input2.attr("value",companyId);form.append(input2);form.submit();//表單提交})
2)post請(qǐng)求
$('.download').click(function(){var tt =newDate().getTime();var url = restUrl +'/excel/download?userId='+ userId;var form=$("<form>");//定義一個(gè)form表單form.attr("style","display:none");form.attr("target","");form.attr("method","post");//請(qǐng)求類型form.attr("action",url);//請(qǐng)求地址$("body").append(form);//將表單放置在web中var input1=$("<input>");input1.attr("type","hidden");input1.attr("name","tt");input1.attr("value",tt);form.append(input1);var input2=$("<input>");input2.attr("type","hidden");input2.attr("name","companyId");input2.attr("value",companyId);form.append(input2);form.submit();//表單提交});
完成后,在頁面上面點(diǎn)擊下載圖標(biāo),文件就會(huì)自動(dòng)下載了。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注