如何在输入所需密钥的文件下载时重命名或仅保留文件名?

How to rename or keep the file name only while downloading the file entering a required key?

看我下面的代码。它工作正常,但是在通过输入所需的密钥下载文件时,文件名发生了变化,并且正在下载整个域名+目录+文件名。但我只想要文件名。

代码:

//这是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>

有多种方法可以解决您的问题。最简单的解决方案是将 download 属性设置为没有值

link.download = '';

这将使用 URL 的最后一段作为文件名。

download

Causes the browser to treat the linked URL as a download. Can be used with or without a value:

Without a value, the browser will suggest a filename/extension, generated from various sources:

  • The Content-Disposition HTTP header
  • The final segment in the URL path
  • The media type (from the Content-Type header, the start of a data: URL, or Blob.type for a blob: URL)

Defining a value suggests it as the filename. / and \ characters are converted to underscores (_). Filesystems may forbid other characters in filenames, so browsers will adjust the suggested name if necessary.

MDN