Possible to generate a file in javascript and prompt the user to download?
Is it possible to generate a file in javascript and then prompt the user to download ?
What we would really like to do is the following : we want to make a small html form where an user can edit values in a table, and we would like to be able to generate a csv file from the form and prompt the user to save it on his hard drive. Is it possible in pure javascript ? If not, are there any workarounds ?
Note : I know I could solve this by a round-trip to a server, 开发者_运维问答sending the form and getting a csv file back, but the trick here is that there is no server, the html form will just be generated on a hard drive.
Without a server to download from, you cant get them to download the data like normal.
You could output the csv data to a new browser window and the user could then save this.
If you don't mind using flash, I suggest you use Downloadify. You host downloadify.swf
that you will serve with your javascript content generating code.
It is easy to integrate. Here is a cut&paste from the provided sample web site :
<script type="text/javascript">
Downloadify.create('downloadify',{
filename: function(){
return document.getElementById('filename').value;
},
data: function(){
return document.getElementById('data').value;
},
onComplete: function(){
alert('Your File Has Been Saved!');
},
onCancel: function(){
alert('You have cancelled the saving of this file.');
},
onError: function(){
alert('You must put something in the File Contents or there will be nothing to save!');
},
transparent: false,
swf: 'media/downloadify.swf',
downloadImage: 'images/download.png',
width: 100,
height: 30,
transparent: true,
append: false
});
</script>
In pure javascript, no.
You'd need a server side script to generate the file and save it temporarily/ in memory, and then present a force-download dialogue to the user.
Suggest you take Fungus' route and use javascript to write it to a browser window, then instructing the user how to save it (Copy > Paste ... etc).
Cheers, Sean
精彩评论