高性能序列化库设计与实现:零拷贝与固定Schema实战
2026/10/20 14:21:31
<a href='../a.txt'>下载<a>当前页打开
<a href='../a.txt' target="_blank">下载<a> 或者 <a href='javascript:openfile(src)'>下载<a> openfile(src) { window.open(src, '_blank'); }使用download强制触发下载:
<a href='../a.txt' download>下载<a> 或 <a href='../a.txt' download='a.txt'>下载<a>但实际上txt文件在谷歌浏览器上有点问题,会直接打开。
doc和excel、pdf倒是可以触发下载
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下载会出错。
<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这种方法应该是最合适的。