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

查看:36
本文介绍了如何在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 编码时,浏览器会将内容下载为文件.您必须添加一个 script 或 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天全站免登陆