2017-03-07 27 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"); 

}

相關問題