javascript - 如何制作一个触发下载用户输入的特定键的特定文件的功能?
问题描述
我制作了一个文本框和一个按钮。现在任何人都可以帮我做一个功能,我怎么能做到这一点?
我希望用户输入一个特定的字母数字键,该键将由网站以其他方式给出。它将是字母数字。用户必须在文本框中输入密钥,然后单击按钮下载只有字母数字密钥才能访问的特定文件。然后,如果密钥与特定文件匹配,它将被下载。也将有很多其他文件可用,但将下载具有匹配密钥的文件。请帮我...
我的代码:
<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>
解决方案
您可以将要下载的文件数组作为具有文件密钥和完整路径的对象。当用户输入密钥时,您过滤数组并获取文件(如果匹配):
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>
推荐阅读
- python - 如何为sklearn knn制作用户定义的可调用权重函数?
- azure - Azure 共享仪表板未更新
- c# - 在 Linq 查询中使用表达式的正确语法是什么?
- c# - Child 在运行时忽略 Parent 的变换位置的变化。怎么修?
- firebase - 我可以通过更新 y firebase 实时数据库来自动启动我的应用程序吗?
- asp.net-core - INotificationConfiguration 不包含“通知程序”的定义
- ios - iOS - 渐变之间的过渡?
- java - 上下文右键单击将链接另存为
- python - 我想在我的表单中将图像字段设为可选。我尝试了空白 = True 但它不起作用?
- kubernetes - 在 2 个区域之间平衡 redis 集群