如何使用 HTML 5 从服务器访问和下载文件
我目前正在开发一个网站,用户可以从中下载二进制媒体文件(主要是.mp3)。我们需要一种方法让“下载”按钮将文件保存到用户在浏览器首选项中指定的位置,并且它需要以某种方式显示进度条。
目前,我所担心的是找到一种使用 HTML5 来实现这一点的方法,并以这样的方式进行:在未来的版本中,我们稍后将能够访问该流,这样一旦我们对这个基本下载部分进行了编码,我们就可以以某种方式在未来实现一个进度条。
我知道 HTML5 有一个文件 API,但目前很少有浏览器允许它的实现,我们需要它在 IE 7+ 以及常用版本的 Chrome 和 Firefox 上工作。
感谢您的帮助!
I am currently working on a website that users can download binary media files from (mainly .mp3). We need a way for a "Download" button to save the file to the user's specified location in their browser's preferences, and it needs to somehow display a progress bar.
Currently, all I'm worried about is finding a way to implement this using HTML5 and doing it in such a way that in future versions we will later be able to access that stream so that once we get this basic download part coded, we can somehow implement a progress bar in the future.
I know HTML5 has a File API, but very few browsers currently allow its implementation, and we need this to work on IE 7+ and regularly used versions of Chrome and Firefox.
Thanks for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
HTML5 支持
download
属性:http://webreflection.blogspot.com/2011/08/html5-how-to-create-downloads-on-fly.html示例:
单击此按钮将允许浏览器处理下载(而不是使用与 mimetype 关联的任何应用程序打开文件),包括进度条。
注意:您确实需要小心,不要尝试创建自己的实现来偏离正常用户的期望。这与强制链接在新选项卡中打开是同义的 - 如果用户期望一种行为但收到另一种行为,则可能会让用户感到困惑。对于您的情况,请尝试具体解释这将是“下载”链接,而不是“播放”链接。上面的示例就是这样做的,但“下载”图标也可能就足够了。
HTML5 supports the
download
attribute: http://webreflection.blogspot.com/2011/08/html5-how-to-create-downloads-on-fly.htmlExample:
Clicking on this will allow the browser to handle the download (instead of opening the file using whatever application is associated with the mimetype), including a progress bar.
Note: You really want to be careful not to deviate from normal user expectation by trying to create your own implementation. This is synonymous with forcing a link to open in a new tab--it can be confusing to the user if they are expecting one behavior but receive another. In your case, try to specifically explain that this will be a "download" link, not a "play" link. The example above does this, but a "download" icon might also suffice.
只需将 download 属性添加到 HTML5 中的锚标记即可。
Just put the download attribute to your anchor tag in HTML5.
如果您想让下载链接成为一个按钮,您只需在
中放置一个
元素即可:
您还可以使用 DOM动态更改元素的
href
。我的博客中的示例,其中有问题的下载按钮基本上是“另存为”按钮:希望这会有所帮助......
If you want to make the download link a button instead, you can just place an
<input>
element inside an<a>
:And you can also use DOM to dynamically change the
href
of the element. Example from my blog, where the download button in question is basically a "Save as" button:Hope this helps...