恒美微站
首页
关于我们
建站服务
主题模板
案例展示
资讯中心
联系我们
H5超链接实现下载文件
首页
资讯中心
/
H5超链接实现下载文件
H5超链接实现下载文件
发布时间:2026/10/20 13:26:37
文章目录1、超链接访问2、其他页打开3、下载4、下载txt4、改进1、超链接访问a href../a.txt下载a当前页打开2、其他页打开a href../a.txt target_blank下载a 或者 a hrefjavascript:openfile(src)下载a openfile(src) { window.open(src, _blank); }3、下载使用download强制触发下载a href../a.txt download下载a 或 a href../a.txt downloada.txt下载a但实际上txt文件在谷歌浏览器上有点问题会直接打开。doc和excel、pdf倒是可以触发下载4、下载txtopenfile(src, name) { const fileUrl PATH src; const fileName name; fetch(fileUrl) .then(response { if (!response.ok) throw new Error(网络响应不正常); return response.text(); }) .then(text { try { const base64 btoa(unescape(encodeURIComponent(text))); const dataUrl data:text/plain;base64,${base64}; const link document.createElement(a); link.href dataUrl; link.download fileName; document.body.appendChild(link); link.click(); return; } catch (e) {} }) }但只试用于txt, doc、excel、图片、PDF下载会出错。4、改进text clickopenfile(src,name) 下载/text openfile(src, name) { const fileUrl src; const fileName name; fetch(fileUrl) .then(response { if (!response.ok) { throw new Error(网络响应不正常); } return response.blob(); }) .then(blob { const link document.createElement(a); link.href URL.createObjectURL(blob); link.download fileName; document.body.appendChild(link); link.click(); document.body.removeChild(link); }) .catch(error { console.error(下载文件时出错:, error); }); } //ajax版本 var getTemp function (src, name) { const fileUrl src; const fileName name; //const fileUrl site /upload/InsertTemple.xlsx; //const fileName InsertTemple; $.ajax({ url: fileUrl, type: GET, xhrFields: { responseType: blob }, beforeSend: function () { // 打开加载提示 }, success: function (blob) { const link document.createElement(a); link.href URL.createObjectURL(blob); link.download fileName; document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(link.href); }, complete: function () { // 关闭加载提示 }, error: function (xhr, err) { console.error(下载文件时出错:, err); } }) }实测各类型文件都能下载成功。因为H5无法使用 uni.downloadFile后端是webapi 无法使用response。所以H5这种方法应该是最合适的。