如何设置从浏览器下载的文件名?

Spa*_*ile 50 html download savefiledialog

我正在编写一个Web应用程序,除其他外,它允许用户将文件上传到我的服务器.为了防止名称冲突和组织文件,我将它们放在我的服务器上后重命名.通过跟踪原始文件名,我可以与文件的所有者进行通信,而他们不知道我在后端更改了文件名.也就是说,直到他们去下载文件.在这种情况下,系统会提示他们下载一个名称不熟悉的文件.

我的问题是,有没有办法只使用HTML指定要下载的文件的名称?因此,用户上传名为'abc.txt'的文件并将其重命名为'xyz.txt',但是当他们下载它时,我希望浏览器默认将文件保存为'abc.txt'.如果仅使用HTML无法做到这一点,有没有办法做到这一点?

Pal*_*tir 60

无法在HTML中找到方法.我想你需要一个服务器端脚本来输出内容处理头.在PHP中,这样做:

header('Content-Disposition: attachment; filename="downloaded.pdf"');
Run Code Online (Sandbox Code Playgroud)

如果你想提供一个默认的文件名,但不是自动下载,这似乎有效.

header('Content-Disposition: filename="filetodownload.jpg"');
Run Code Online (Sandbox Code Playgroud)

实际上,它是直接为您的文件提供服务的服务器,因此您无法通过HTML与其进行交互,因为HTML根本不涉及.


Mep*_*les 47

当他们单击按钮下载文件时,您可以添加HTML5属性download,您可以在其中设置默认文件名.

这就是我做的,当我创建一个xlsx文件并且浏览器想要将其保存为zip文件时.

<a href="path/to/file" download="renamed.txt">Download</a>
<a href="downloads/export.xlsx" download="Data-Export.xlsx">Download Export</a>
Run Code Online (Sandbox Code Playgroud)

  • "download"属性仅适用于具有相同来源的资源的链接. (11认同)
  • 如果filesize不可读或省略myfilename,有时download ="myfilename"将不起作用. (3认同)
  • 这取决于文件大小是否可读?我不知道...但我想我记得我遇到了一些不想重命名的文件的问题...也许这可能是问题...好吧...就我而言,文件来自机架空间,所以我无法访问标题:D (2认同)

xgq*_*rms 7

只需要使用HTML5a标签download属性

codepen现场演示

https://codepen.io/xgqfrms/full/GyEGzG/

我的屏幕快捷方式。

在此输入图像描述

在此输入图像描述

更新答案

  1. 文件是否可下载取决于服务器的响应配置,例如Content-Type, Content-Disposition

  2. 下载文件extensions是可选的,也取决于服务器的配置。

'Content-Type': 'application/octet-stream',
// it means unknown binary file,
// browsers usually don't execute it, or even ask if it should be executed.

'Content-Disposition': `attachment; filename=server_filename.filetype`,
// if the header specifies a filename,
// it takes priority over a filename specified in the download attribute.
Run Code Online (Sandbox Code Playgroud)

下载blob网址文件

'Content-Type': 'application/octet-stream',
// it means unknown binary file,
// browsers usually don't execute it, or even ask if it should be executed.

'Content-Disposition': `attachment; filename=server_filename.filetype`,
// if the header specifies a filename,
// it takes priority over a filename specified in the download attribute.
Run Code Online (Sandbox Code Playgroud)

https://cdn.xgqfrms.xyz/HTML5/Blob/index.html

参考文献

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#download

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition

https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#important_mime_types_for_web_developers

  • 这不起作用,至少在 chrome 上是这样。当我尝试时,它只是说“失败 - 无文件”或“失败 - 服务器问题”。 (2认同)