2017-03-07 28 views
1

我想要做什么:指定一条路线(使用iron-router),它在访问时启动文件下载。该文件包含来自应用程序mongo-Databases的信息。如何使用铁路由器(和ground-db)作为文件下载mongo集合?

使用案例:我正在开发一个流星离线 Web的应用程序,它也被导出为Android应用程序。在应用程序内,用户可以保存多个不同的数据/信息。用户应该能够从应用程序内部导出和导入数据(例如,当他想切换设备时)。 可能有一个解决方案,与我的(这个)方法完全不同,我当然也是这样做的。

其他信息:我蒙戈的数据库是本地(客户端)使用groundDB。 如果当流星应用程序以android应用程序的形式运行时,解决方案也可以工作,那将是完美的。该文件的实际格式很小(类似csv/json/...)。

当前的方法:

// Define route... 
Router.route('/download', function(){ 
/** 
* Combine data from different Mongo 
* Collections in one js variable in JSON format: 
**/ 
    var dataToDownload = []; 
    dataToDownload[0] =  Collection.find().fetch(); 
    dataToDownload[1] = AnotherCollection.find().fetch(); 

/** 
* Convert JSON to string for download (not sure 
* if necessary?!): 
**/ 
    var data = "text/json;charset=utf-8," 
    + encodeURIComponent(JSON.stringify(dataToDownload)); 

/** 
* This obviosly doesn't work since it's trying to 
* render a template which has the name equal to 
* my JSON string: 
**/ 
    this.render(data); 
}); 

基本上我寻找的东西来代替this.render(data); with sth。是那(在伪代码中)this.download(data);

+0

客户端,我认为你的模拟“下载”唯一的选择就是location.href设置为dataurl –

+0

看到http://stackoverflow.com/questions/3916191/download-上data-url-file –

+1

谢谢,那是我需要的食物。 – zwif

回答

0

我没有设法找到解决方案,其中涉及铁路路由器。但另一个直接的解决方案,如'Download data url file':

只需创建一个带有集合数据的Blob,为其创建ObjectURL并使用锚点(<a id="anchor">Download</a>)开始下载。

var blob = new Blob([JSON.stringify(dataToDownload, null, 2)], {type : 'application/json'}); 
var url = URL.createObjectURL(blob); 

$('#anchor').attr("href", url); 
$('#anchor').attr("download", "someName"); 

}

相关问题