Advertisement
Guest User

Untitled

a guest
Jun 20th, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. function saveTextAsFile()
  2. {
  3. var textToWrite = //Your text input;
  4. var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
  5. var fileNameToSaveAs = //Your filename;
  6.  
  7. var downloadLink = document.createElement("a");
  8. downloadLink.download = fileNameToSaveAs;
  9. downloadLink.innerHTML = "Download File";
  10. if (window.webkitURL != null)
  11. {
  12. // Chrome allows the link to be clicked
  13. // without actually adding it to the DOM.
  14. downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
  15. }
  16. else
  17. {
  18. // Firefox requires the link to be added to the DOM
  19. // before it can be clicked.
  20. downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
  21. downloadLink.onclick = destroyClickedElement;
  22. downloadLink.style.display = "none";
  23. document.body.appendChild(downloadLink);
  24. }
  25.  
  26. downloadLink.click();
  27. }
  28.  
  29. My text area:<br />
  30. <textarea rows='10' cols='80' id='myTextArea' ></textarea>
  31.  
  32. <br /><br />
  33.  
  34. Download button: <br />
  35. <input value='download' type='button'
  36. onclick='doDL(document.getElementById("myTextArea").value)' />
  37.  
  38.  
  39. <script type='text/javascript'>
  40. function doDL(s){
  41. function dataUrl(data) {return "data:x-application/text," + escape(data);}
  42. window.open(dataUrl(s));
  43. }
  44. </script>
  45.  
  46. function doDownload(str) {
  47. function dataUrl(data) {
  48. return "data:x-application/xml;charset=utf-8," + escape(data);
  49. }
  50. var downloadLink = document.createElement("a");
  51. downloadLink.href = dataUrl(str);
  52. downloadLink.download = "foo.xml";
  53.  
  54. document.body.appendChild(downloadLink);
  55. downloadLink.click();
  56. document.body.removeChild(downloadLink);
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement