☰
H5超链接实现下载文件
2026/10/20 13:26:36 网站建设 项目流程

文章目录

  • 1、超链接访问
  • 2、其他页打开
  • 3、下载
  • 4、下载txt
  • 4、改进

1、超链接访问

<a href='../a.txt'>下载<a>

当前页打开

2、其他页打开

<a href='../a.txt' target="_blank">下载<a> 或者 <a href='javascript:openfile(src)'>下载<a> openfile(src) { window.open(src, '_blank'); }

3、下载

使用download强制触发下载:

<a href='../a.txt' download>下载<a> 或 <a href='../a.txt' download='a.txt'>下载<a>

但实际上txt文件在谷歌浏览器上有点问题,会直接打开。
doc和excel、pdf倒是可以触发下载

4、下载txt

openfile(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 @click="openfile(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这种方法应该是最合适的。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询