Javascript下载字符串 [英] Javascript to Download String

查看:84
本文介绍了Javascript下载字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在Javascript中启动浏览器下载,但我想要下载的数据是字符串,而不是文件。我知道如果它是一个文件,下面会这样做:

Trying to initiate a browser download in Javascript, but the data I want to be downloaded is in a string, not a file. I know if it were a file, the following would do it:

window.location.href = '/filepath/file.csv';

如何才能获得同样的效果,只能使用字符串(使用csv数据),而不是文件已经存在于服务器上?

How can I get this same effect, only with a string (with csv data), not a file that already exists on the server?

推荐答案

使用我方便的下载器:

<script src="http://danml.com/js/download.js"></script>
<script>download("hello world", "hello.txt", "text/plain")</script>

你可以在没有图书馆的情况下做到这一点,虽然我的lib不是很大,支持较旧的FF + CH和IE10:

you can do it without a library as well, though my "lib" isn't very big and supports older FF+CH and IE10:

<a id=dl download="file.txt">Download</a>
<script>
content=prompt("enter contents");
dl.href="data:text/plain,"+encodeURIComponent(content);
dl.click();
</script>

编辑:链接脚本现在支持window.URL.createObjectURL(),用于下载太大的文件使用dataURLs。我不知道新的限制,但10mb只能用于文件,而~2mb是许多dataURL的限制(window.open/A[download] - 基于)solutions3

the linked script now supports window.URL.createObjectURL() for downloading files that were too big using dataURLs. I don't know the new limit, but 10mb works just file, whereas ~2mb is a limit for many dataURL ( window.open/A[download] - based ) solutions3

这篇关于Javascript下载字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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