首页 > 解决方案 > 如何制作一个触发下载用户输入的特定键的特定文件的功能?

问题描述

我制作了一个文本框和一个按钮。现在任何人都可以帮我做一个功能,我怎么能做到这一点?

我希望用户输入一个特定的字母数字键,该键将由网站以其他方式给出。它将是字母数字。用户必须在文本框中输入密钥,然后单击按钮下载只有字母数字密钥才能访问的特定文件。然后,如果密钥与特定文件匹配,它将被下载。也将有很多其他文件可用,但将下载具有匹配密钥的文件。请帮我...

我的代码:

<center>
        <input class="keyBox" type="text" placeholder="Enter your download key">
        <br><br>
        <div class="text-center">
            <button type="submit" class="btn btn-style btn-primary">Download</button>
        </div>
        </button>
  </center>

标签: javascripthtmljquerycssdownload

解决方案


您可以将要下载的文件数组作为具有文件密钥和完整路径的对象。当用户输入密钥时,您过滤数组并获取文件(如果匹配):

const files = [
  { key: 1, path: "200" },
  { key: 2, path: "100" },
  { key: 3, path: "300" },
];
const globalPath = "https://picsum.photos/";
const inp = document.querySelector(".keyBox");
const btn = document.querySelector("#down");
btn.addEventListener("click", downloadURI);
function downloadURI() {
  if (inp.value) {
    let uri = files.filter((f) => f.key === Number(inp.value));
    if (uri.length) {
      const fullPath = globalPath + uri[0].path;
      fetch(fullPath)
        .then((resp) => resp.blob())
        .then((blob) => {
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.style.display = uri[0].path;
          a.href = url;
          // the filename you want
          a.download = uri[0].path;
          document.body.appendChild(a);
          a.click();
          window.URL.revokeObjectURL(url);
        })
        .catch(() => alert("An error sorry"));
    }
  } else {
    console.log("no such file");
  }
}
<center>
  <input class="keyBox" type="text" placeholder="Enter your download key">
  <br><br>
  <div class="text-center">
    <button id="down" class="btn btn-style btn-primary">Download</button>
  </div>
</center>


推荐阅读