如何创建一个动态文件+链接在Javascript中下载? [英] How to create a dynamic file + link for download in Javascript?

查看:136
本文介绍了如何创建一个动态文件+链接在Javascript中下载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,HTML页面可以链接到可从服务器下载的文档(PDF等)。

Typically, HTML pages can have link to documents (PDF, etc...) which can be downloaded from the server.

假设启用Javascript的网页是可以从用户浏览器内动态创建文本文档(例如),并添加一个链接来下载此文档,而无需往返服务器(或最小的一个)?

Assuming a Javascript enabled webpage, is it possible to dynamically create a text document (for example) from within the user browser and add a link to download this document without a round trip to the server (or a minimal one)?

换句话说,用户将点击一个按钮,JavaScript将生成随机数(例如),并将它们放在一个结构中。然后,javascript(例如JQuery)将添加一个链接到页面,从结构中以文本文件形式下载结果。

In other word, the user would click on a button, the javascript would generate randoms numbers (for example), and put them in a structure. Then, the javascript (JQuery for example) would add a link to the page to download the result as a text file from the structure.

这个目标是保留所有或至少大多数)在用户端的工作负载。

This objective is to keep all (or at least most) of the workload on the user side.

这是可行的,如果是,如何?

Is this feasible, if yes how?

推荐答案

通过在页面中附加数据URI ,您可以在可以下载的页面中嵌入文档。字符串的数据部分可以使用Javascript动态连接。您可以选择将其格式化为URL编码字符串或作为base64编码。当它是base64编码时,浏览器将以内容作为文件下载。您必须添加脚本或jQuery插件才能进行编码。这里有一个静态数据的例子:

By appending a data URI to the page, you can embed a document within the page that can be downloaded. The data portion of the string can be dynamically concatenated using Javascript. You can choose to format it as a URL encoded string or as base64 encoded. When it is base64 encoded, the browser will download the contents as a file. You will have to add a script or jQuery plugin to do the encoding. Here is an example with static data:

jQuery('body').prepend(jQuery('<a/>').attr('href','data:text/octet-stream;base64,SGVsbG8gV29ybGQh').text('Click to download'))

这篇关于如何创建一个动态文件+链接在Javascript中下载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆