How can i generate a file and offer it for download in plain javascript?

匿名 (未验证) 提交于 2019-12-03 01:48:02

问题:

I would like to generate a text file in the javascript dynamicly, then offer this for download. Currently I can get this working to a degree with either of the following solutions:

content = "abc123"; document.location = "data:text/octet-stream," + encodeURIComponent(content); 

OR

content = "abc123";     var bb = new BlobBuilder(); bb.append(content); var blob = bb.getBlob(); blob = blob.slice(0, blob.size, 'text/octet-stream'); var fr = new FileReader();  fr.onload = function() {document.location = this.result;} fr.readAsDataURL(blob); 

However, Both of these solutions, when the download box appears, will only offer a default filename of 'download' in the save as dialogue.

My question is basically, how can I change this to a specific filename for example 'readme.txt' or 'scene.obj'

Also note the data type was previously 'text/plain' however if this is used, the document switches to the new text document instead of offering it for download (as text/octet-stream seems to do).

I do not want a flash solution, javascript/html5 only suggestions please.

Cheers, Josh

回答1:

For that, you will have to use FileSaver from FileAPI: Writer specification. For now, it's only a draft, and according to mailing list answer it isn't yet implemented in browsers.

You can watch for example on a chromium issue to get up-to-date information about the implementation progress

UPD 02.08.2013: I have since found a project that provides FileSaver interface using neat tricks



回答2:

I think you should check: jQuery Table to CSV export



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!