You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTML download属性(JS实现):无扩展名文件下载自动变.txt问题

解决无扩展名文件下载自动变为.txt的问题

问题核心是浏览器会根据文件的MIME类型自动添加扩展名,当返回的Blob类型为text/plain时,就会默认追加.txt后缀。要生成无扩展名的文件,需要强制指定文件的MIME类型为application/octet-stream(二进制流类型),让浏览器不再自动推断扩展名。

修改JavaScript代码方案

将File构造函数的type参数从blob.type改为'application/octet-stream':

document.getElementById('download-link').addEventListener('click', function(event) {
  event.preventDefault();
  const url = this.href;
  const filename = 'install_scanshield';

  fetch(url)
    .then(response => response.blob())
    .then(blob => {
      const file = new File([blob], filename, {
        type: 'application/octet-stream' // 强制指定二进制流类型
      });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(file);
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(link.href);
    })
    .catch(console.error);
});

简化方案(无需JS处理)

你HTML中的<a>标签已经设置了download="install_scanshield",如果不需要额外的fetch逻辑,直接去掉JavaScript代码即可,浏览器会按照download属性指定的文件名直接下载,不会自动添加.txt后缀:

<a id="download-link" class="btn btn-primary rounded-pill px-3 text-decoration-none" style="color: black" href="https://gist.githubusercontent.com/INeddHelp/d8dd652f2ce8ac52fa6e6c19cbaaaac4/raw/79cd683fe0338aa557b26fbc1fe3d8ac15bdfb48/install_scanshield"
  download="install_scanshield">
  Download
  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-download" viewBox="0 0 16 16">
    <path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5"/>
    <path d="M7.646 11.854a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L8.5 10.293V1.5a.5.5 0 0 0-1 0v8.793L5.354 8.146a.5.5 0 1 0-.708.708z"/>
  </svg>
</a>

内容的提问来源于stack exchange,提问作者Michael Barati

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 14:20:09