2016-12-06 64 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”的文件,但您可以根据需要进行调整。