如何在输入所需密钥的文件时仅重命名或保留文件名?
请参阅我的下面代码。它工作正常,但是在输入所需键下载文件时,文件名更改,并使用整个域名 +目录 +文件名下载。但是我只想要文件名。
代码:
//这是HTML部分。
<center>
<input class="keyBox" style="padding : 10px; padding-left:15px; padding-right:15px" type="text" width="100px" placeholder="Enter your download key">
<br><br>
<div class="text-center">
<button id="down" class="btn btn-style btn-primary">Download</button>
</div>
</center>
//这是我正在使用的脚本。
<script>
const files = [{
key: 12345,
path: 'Marouf.png'
}, {
key: 12477,
path: 'Ismat.png'
}]
const globalPath = 'https://abcd.com/directory/certificates/'
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) {
let link = document.createElement("a");
const fullPath = globalPath + uri[0].path
link.download = fullPath;
link.href = fullPath;
link.click();
} else {
alert("Incorrect download key! Try again...")
}
}
}
</script>
See my below code. It's working fine but while downloading a file by entering the required key, the file name changed and it's downloading with the whole domain name + directory + file name. But I want just the file name.
Code :
//This is the HTML part.
<center>
<input class="keyBox" style="padding : 10px; padding-left:15px; padding-right:15px" type="text" width="100px" placeholder="Enter your download key">
<br><br>
<div class="text-center">
<button id="down" class="btn btn-style btn-primary">Download</button>
</div>
</center>
// This is the Script I am using.
<script>
const files = [{
key: 12345,
path: 'Marouf.png'
}, {
key: 12477,
path: 'Ismat.png'
}]
const globalPath = 'https://abcd.com/directory/certificates/'
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) {
let link = document.createElement("a");
const fullPath = globalPath + uri[0].path
link.download = fullPath;
link.href = fullPath;
link.click();
} else {
alert("Incorrect download key! Try again...")
}
}
}
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有多种方法可以解决您的问题。最简单的解决方案是设置
下载
属性而无需值,这将使用URL的最终段作为文件名。
mdn
There are multiple ways to solve your problem. The most simple solution is to set the
download
attribute without valueThis will use the final segment of the URL as filename.
MDN