编程技术网

关注微信公众号,定时推送前沿、专业、深度的编程技术资料。

 找回密码
 立即注册

QQ登录

只需一步,快速开始

极客时间

是否可以仅使用 JavaScript(客户端方法)在浏览器中为已识别的 MIME 类型启动下载提示?:Is it possible to initiate a download prompt in the browser for recognized MIME types using only JavaScript (client-side approach)?

X-neuron 机器学习 2022-5-7 10:19 8人围观

腾讯云服务器
是否可以仅使用 JavaScript(客户端方法)在浏览器中为已识别的 MIME 类型启动下载提示?的处理方法

我希望允许用户通过单击直接下载文件.然而,当涉及到已知的 MIME 类型(如 HTML、音频、视频等)时,存在一个问题.理想情况下,我想触发音频/视频文件的下载提示.最终,我也想为 HTML 文档做这件事.主要思想是让用户可以轻松下载文件,而无需要求他们导航到上下文菜单.

I would like to allow the user to directly download a file with a single click. There is however a problem when it comes to known MIME types like HTML, audio, video, etc. Ideally, I would like to trigger a download prompt for audio/video files. Ultimately, I would like to do it for HTML documents too. The main idea is to make it easy for users to download files without asking them to navigate into the context menu.

我认为例如对于对计算机及其主要功能不太满意的人.这些人肯定会喜欢比另存为"更好的方法.

I think for example to people that are not really comfortable with a computer and its main functions. These people will surely prefer a better way than "save as".

我寻找 JavaScript 解决方案的原因是 PHP 方法仅在您处于网站上下文中时才有效.每当您在插件或注入的脚本上下文中(即为 Firefox、Chrome 或 Safari 开发插件)时,您可能希望避免请求服务器端响应.

The reason why I am looking for a JavaScript solution is that the PHP approach only works if you are in a web site context. Whenever you are inside a plugin or injected script context (i.e. developing a plugin for Firefox, Chrome or Safari), you may want to avoid asking for a server-side response.

我尝试使用 window.open()document.execCommand("saveAs",... 来实现这一点.它确实有效,尽管它有问题并且对于大文件失败.

I tried to achieve this with window.open() and document.execCommand("saveAs",.... It does work, although it is glitchy and fails for huge files.

然后,我尝试了 Downloadify,但它并不适用于所有情况.

Then, I tried Downloadify which does not work in every situations.

是否有纯 JavaScript 的,没有 Ajax 方式来触发下载提示,以便用户可以通过简单的左键单击直接下载文件?

Is there a pure JavaScript, no Ajax way to trigger a download prompt so the user can directly download a file using a simple left click?

问题解答

HTML5 中有一个新的 download 属性,您可以用它来注释链接.它向浏览器指示应该下载资源而不是导航到该资源.目前,它仅适用于 Chrome,但它是 HTML 规范的一部分,有望很快被其他浏览器采用.

There is a new download attribute in HTML5 that you can annote links with. It indicates to the browser that the resource should be downloaded rather than navigated to. Right now, it only works in Chrome, but it is part of the HTML spec and will hopefully be adopted by other browser soon.

演示:http://html5-demos.appspot.com/static/a.下载.html更多信息:http://updates.html5rocks.com/2011/08/Downloading-resources-in-HTML5-a-download

这篇关于是否可以仅使用 JavaScript(客户端方法)在浏览器中为已识别的 MIME 类型启动下载提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程技术网(www.editcode.net)!

腾讯云服务器 阿里云服务器
关注微信
^