Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

javascript - 单击HTML按钮或JavaScript时如何触发文件下载(How to trigger a file download when clicking an HTML button or JavaScript)

This is crazy but I don't know how to do this, and because of how common the words are, it's hard to find what I need on search engines.

(这太疯狂了,但是我不知道该怎么做,而且由于这些单词很常见,因此很难在搜索引擎上找到我需要的东西。)

I'm thinking this should be an easy one to answer.

(我认为这应该很容易回答。)

I want a simple file download, that would do the same as this:

(我想要一个简单的文件下载,该操作与此相同:)

<a href="file.doc">Download!</a>

But I want to use an HTML button, eg either of these:

(但是我想使用HTML按钮,例如以下任一按钮:)

<input type="button" value="Download!">
<button>Download!</button>

Likewise, is it possible to trigger a simple download via JavaScript?

(同样,是否可以通过JavaScript触发简单下载?)

$("#fileRequest").click(function(){ /* code to download? */ });

I'm definitely not looking for a way to create an anchor that looks like a button, use any back-end scripts, or mess with server headers or mime types.

(我绝对不是在寻找一种创建类似于按钮的锚,使用任何后端脚本或与服务器标头或mime类型混淆的方法。)

  ask by brentonstrine translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can trigger a download with the HTML5 download attribute.

(您可以使用HTML5 download属性触发download 。)

<a href="path_to_file" download="proposed_file_name">Download</a>

Where:

(哪里:)

  • path_to_file is a path that resolves to an URL on the same origin .

    (path_to_file是可解析为同一来源的URL的路径)

    That means the page and the file must share the same domain, subdomain, protocol (HTTP vs. HTTPS), and port (if specified).

    (这意味着页面和文件必须共享相同的域,子域,协议(HTTP与HTTPS)和端口(如果指定)。)

    Exceptions are blob: and data: (which always work), and file: (which never works).

    (blob:data:始终有效)和file:永远无效)是例外。)

  • proposed_file_name is the filename to save to.

    (proposed_file_name是要保存到的文件名。)

    If it is blank, the browser defaults to the file's name.

    (如果为空,则浏览器默认为文件名。)

Documentation: MDN , HTML Standard on downloading , HTML Standard on download , CanIUse

(文档: MDN正在下载的 HTML标准,正在download HTML标准CanIUse)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...