问题描述
我有以下代码让用户下载csv文件中的数据字符串。
I have the following code to let users download data strings in csv file.
exportData = 'data:text/csv;charset=utf-8,';
exportData += 'some csv strings';
encodedUri = encodeURI(exportData);
newWindow = window.open(encodedUri);
如果客户端运行代码它会生成空白页并开始下载csv中的数据文件。
It works just fine that if client runs the code it generates blank page and starts downloading the data in csv file.
所以我尝试用JSON对象做这个,比如
So I tried to do this with JSON object like
exportData = 'data:text/json;charset=utf-8,';
exportData += escape(JSON.stringify(jsonObject));
encodedUri = encodeURI(exportData);
newWindow = window.open(encodedUri);
但我只看到一个显示JSON数据的页面,而不是下载它。
But I see only a page with the JSON data displayed on it, not downloading it.
我进行了一些研究并且声称可以使用,但我认为我的代码没有任何区别。
I went through some research and this one claims to work but I don't see any difference to my code.
我在代码中遗漏了什么?
Am I missing something in my code?
感谢您阅读我的问题:)
Thanks for reading my question:)
推荐答案
这是怎么回事我为我的申请解决了这个问题:
This is how I solved it for my application:
HTML:
< a id =downloadAnchorElemstyle =display:none> ;< / a>
JS(纯JS,这里不是jQuery):
JS (pure JS, not jQuery here):
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(storageObj));
var dlAnchorElem = document.getElementById('downloadAnchorElem');
dlAnchorElem.setAttribute("href", dataStr );
dlAnchorElem.setAttribute("download", "scene.json");
dlAnchorElem.click();
在这种情况下, storageObj
是js您要存储的对象,scene.json只是生成文件的示例名称。
In this case, storageObj
is the js object you want to store, and "scene.json" is just an example name for the resulting file.
此方法与其他提议的方法相比具有以下优点:
This approach has the following advantages over other proposed ones:
- 不需要点击HTML元素
- 结果将按您的要求命名
- 不需要jQuery
我需要这种行为而不需要明确点击,因为我想在某些情况下自动触发下载点js。
I needed this behavior without explicit clicking since I want to trigger the download automatically at some point from js.
JS解决方案(不需要HTML):
JS solution (no HTML required):
function downloadObjectAsJson(exportObj, exportName){
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(exportObj));
var downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute("href", dataStr);
downloadAnchorNode.setAttribute("download", exportName + ".json");
document.body.appendChild(downloadAnchorNode); // required for firefox
downloadAnchorNode.click();
downloadAnchorNode.remove();
}
这篇关于从浏览器下载JSON对象作为文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!