2016-12-06 60 views
0

有沒有辦法生成一些帶有JSON內容的文件並用saveAs對話框提示用戶。從Word對話框生成並下載文件

這是來自單詞中的開放對話。

對象也能像(將在實踐中相當大很多)

var obj = {a: 1, b: 2, c: 'qwerty'}

我試圖URI編碼,並使用window.open沒有任何的運氣。

content = JSON.stringify(obj); 
uriContent = "data:application/octet-stream," + encodeURIComponent(content); 
newWindow = window.open(uriContent, 'filename'); 

回答

0

我爲XML做了這個工作,但它需要一些後端和前端工作。在後端,你需要一些這樣的ASPX:

string filename = "export.xml"; 
byte[] data = Convert.FromBase64String(Request.QueryString[0].Replace("\"", "")); 
string decodedString = System.Text.Encoding.UTF8.GetString(data); 
// set the http content type to "APPLICATION/OCTET-STREAM 
Response.ContentType = "APPLICATION/OCTET-STREAM"; 
System.String disHeader = "Attachment; Filename=\"" + filename + "\""; 
Response.AppendHeader("Content-Disposition", disHeader); 
Response.Flush(); 
Response.Write(decodedString); 

我叫我的「download.aspx」。然後在前端,你必須使用AJAX。這創造了網頁上的表格區域和部隊提交表單的開始下載:

// Helper function to load a form and then send the post results to a 
// new window so that we can get the download button 
function ajax_download(url, data, input_name) { 
    try { 
     $('#form-div').append("<form method='GET' action='" + 
         url + "' target='_blank'>" + 
         "<input type=hidden name='" + input_name + "' value='" + 
         JSON.stringify(data) + "'/></form>"); 
     $('#form-div').find('form').submit(); 
    } catch (err) { 
     showNotification("error", err.description); 
    } 
} 

要調用它,只需使這個從您的JavaScript代碼,你想要這個電話是:

xml = "<xml><data>12345</data></xml>"; 
ajax_download('./Download.aspx', btoa(xml), 'xml'); 

在這種情況下,我的目標是定位XML並始終創建一個名爲「export.xml」的文件,但您可以根據需要進行調整。