开发者

Allowing user to save contents of html list to text file

I'm working on an application (ASP.NET, Webforms) that generat开发者_如何学Goes a list of outputs based on a user input. I want to allow the user to save the contents of said list as text file, or possibly as other filetypes such as .csv. What is the best way to approach this? Can it be done client-side with Javascript?


I think you will need to use ActiveX or Java Applets or Silverlight to do something like that. JavaScript does not have access to local file system.

Another way to go with this is create a file on server (physically or on the fly) and make it available for download to the user. That will get him the save file dialog.

To do this on the fly, create a blank page (without any markup. not even ), set Response.ContentType = 'text/plain' and use Response.Write() to write your content in Page_Load.


You can generate a plain text or csv file purely in client-side JavaScript by constructing and opening a data URI.

Example using jQuery:

window.open(
    'data:text/csv;charset=utf-8,' + 
    escape(
        $('#yourlist li') // <- selector for source data here
            .map(function(){
                // format row here
                return $(this).text();
            })
            .get()
            .join('\r\n')
    )
);

Unfortunately, this technique will not work in IE due to lack of data URI support until IE8 and security restrictions once IE added support for data URIs. You'd have to use an alternative technique for IE, either hitting the server again or using ActiveX / Silverlight / Flash / Java Applet to avoid a round trip for data that is presumably already on the client.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜